This time a bit about Kotlin vs Java syntax. I assume you know Java basics: In this post I'll present some very basic examples of Java code and their Kotlin counterparts.
Hello World
Java "Hello World" looks like this:
Kotlin "Hello World" looks like this:
In Kotlin it's shorter and we don't have to create a class.
Simple class
We'll get to if and loops in a moment, but first let us create a class, which we can use later for further examples.
Java class definition with one field and one method returning String (using if-else if)
Kotlin:
We've already seen most of it: lateinit modifier - it makes it much harder to get a Null Pointer Exception in Kotlin. Method definition looks a but different. Semicolons optional.
Variables and constants
Variable and constant declaration, and then variable assigment in Java:
Variable and constant declaration, and then variable assigment in Kotlin:
var and val instead of <<type>> and final type for, respectively: variables and constants declaration.
Conditional operator?
Printing to console and conditional operator in Java:
Printing to console and if expression, which is analogous to conditional operator, in Kotlin:
println call is shorter... If expression... Well, I guess it's easier to read for novices.
Creating objects
Creating objects in Java:
Creating objects in Kotlin:
Kotlin is shorter.
Lists
Creating a list and adding a new object to it in Java:
Creating a list and adding a new object to it in Kotlin:
This one is interesting: List in Kotlin is immutable, we need to use MutableList. On the other hand, it's easily initialized. I didn't even remember Java ArrayList initalization to be so complicated.
for loops
Iterating over list by index and using "foreach" in Java:
Iterating over list by index and using "foreach" in Kotlin:
That's it for now. To be continued: more control flow, more OOP, other things (exceptions?).
No comments:
Post a Comment