Kotlin Basics: syntax

Kotlin is a great language but it’s more like a subset of Java.
In this article, I will deal with Kotlin basics and see what’s different with Java in terms of syntax, form and types.
Before jumping to the subject, let’s see how Kotlin syntax differs from Java syntax.
Packages and imports
Packages and imports are the same in Kotlin and Java. So let’s skip those.
Functions
In Java, declaring a function must follow some directives:
|
|
Moreover, you need to create a class in order to create a function. So it’s something like this:
|
|
Whereas in Kotlin, you do not need to create a class as it’s not relevant to any class which is more logical. When declaring a function, it must follow the following:
|
|
So for the same example as Java, it will be something like this in Kotlin:
|
|
You might notice several aspects that differ from Java:
- Functions in Kotlin are declared using the
fun
keyword - I did not define the return type of the function: it’s implicit, meaning if not defined, then it’s a
void
orUnit
in Kotlin - I noticed that recent languages declare the argument name first before the argument type, so it’s a bit like Golang
- You do not need to call
System.out
in order to print a message, just callprint
orprintln
- There are NO
;
!!! No need to waste time looking for missing;
!
However, it’s not the only way to declare a function in Kotlin:
|
|
- The return type is not defined, it’s also implicit and it will automatically detect the type from the return type (ie: type inference)
- It’s declared like assigning a variable, but it’s used like a real function:
|
|
Variables
In Java, when you are declaring a variable, you MUST declare its type:
|
|
Whereas in Kotlin, the type inference is really strong:
|
|

Comments
Comments are about the same in Java and Kotlin.
|
|
String interpolation
In Java, when building a String, it’s a bit messy:
|
|
In kotlin, you can use the $
along with {
}
to fetch its data:
|
|
Classes
Declaring a class in Java is done like this:
|
|
In Kotlin, it’s about the same:
|
|
However, when declaring a new instance of the class:
|
|
Whereas in Kotlin, you don’t need the new
keyword:
|
|
For loop
|
|
|
|
- It’s more readable in Kotlin than in Java
- We do not need to specify the
var
orval
keywords, again, it’s implicit
Conclusion
So far, Kotlin brings a lot of “common sense”:
- clever type inference
- removal of the
new
keyword - better function declarations
- readable String templates
- readable for loops
Good and maintainable codes are human readable codes