Kotlin has excellent ergonomics for basic programming and experimentation.
To print to the console in Kotlin we use
println, borrowed from
System.out.println in Java:
and more similar to
Here’s the example in Kotlin:
We’re already reducing syntax clutter!
Kotlin uses curly braces to delimit blocks (like Java, unlike Python) and does not use semicolons to end lines (unlike Java, like Python). (You can use semicolons but they will be ignored. But don’t.)
python = True if (python): print("Braces no, semicolons no") // Tabs v. spaces hell, yes!
Kotlin allows us to easily include variables or complete expressions in our strings. To insert the value of a single variable preface it with a dollar sign:
To insert a complete expression a dollar sign can open a block:
Kotlin supports destructuring assignment to allow us to easily extract properties from objects.
This can be done when assigning variables:
Or when receiving arguments in anonymous functions:
Both the Java and Kotlin examples shown throughout this site are interactive. You can run them using the play button, or by typing "Control-Enter" in the editor.
Java playgrounds come in two styles: snippets and full classes. Snippets allow us to run "loose code" through rewriting magic:
But we can also look at full classes. In this case execution starts in the
main here takes no arguments, no the
String that you would
normally find when starting a Java program from the command line.)
Unlike Java, Kotlin allows us to define top-level methods in our code. For now all Kotlin examples start in the main method: