In Kotlin, variable declarations look a bit different than Java's:
val i : Int = 42
They start with either val
or var
, making the declaration final
("value") or variable.
The type is noted after the name, separated by a :
Thanks to Kotlin's type inference the explicit type declaration can be obmitted if there is an assignment with a type the compiler is able to unambigously detect
Java | Kotlin |
---|---|
int i = 42; | var i = 42 (or var i : Int = 42 ) |
final int i = 42; | val i = 42 |
;
to end statementsequals
/hashCode
methods and field accessorsnew
keyword. Creating objects is done just by calling the constructor like any other method.val a = someMap["key"]
Kotlin uses ==
for equality (that is, calls equals
internally) and ===
for referential identity.
Java | Kotlin |
---|---|
a.equals(b); | a == b |
a == b; | a === b |
a != b; | a !== b |
In Kotlin, if
, try
and others are expressions (so they do return a value) rather than (void) statements.
So, for example, Kotlin does not have Java's ternary Elvis Operator, but you can write something like this:
val i = if (someBoolean) 33 else 42
Even more unfamiliar, but equally expressive, is the try
expression:
val i = try {
Integer.parseInt(someString)
}
catch (ex : Exception)
{
42
}