main
function is the primary entry point
Print to standard output: print("Hello, World!")
Datatypes (almost same as Java)
Int
Long
Short
Byte
Double
Float
String
Char
Boolean
Variables and Constants
val <name> [: <type>] = <value>
var <name> [: <type>] = <value>
Operators
&&
||
and
or
===
!==
Data Structures
val lst = listOf("a", "b", "c")
Listval mp = mapOf("a" to 1, "b" to 2, "c" to 3)
Map<String, Int>val st = setOf("a", "b", "c")
Setmutable
as prefix for variables: val mutList = mutableListOf("a")
Functions
// Syntax
// fun <name>([... <param>: <type>]): <type> { ... }
// fun <name>([... <param>: <type>]) = ...
// Example 1
fun sum(a: Int, b: Int) = a + b
// Example 2
// Unit means void, can be omitted
fun sum(a: Int, b: Int): Unit {
print("$a and $b")
}
Loops
Branching
when
is like switch:
when (x) {
1 -> print("1")
2 -> print("2")
else -> print("None")
}
Optional
?
for nullable type: var x: String? = null
?
in call chain for safe calls: print(x?.length)
!!
to throw if null (like force unwrap x!
in Swift): print(x!!.length)
?:
to get a default value (like x ?? <default>
in Swift): print(x?.length ?: 0)
as?
for safe casting: val anInt: Int? = x as? Int
Class/Objects