Kotlin
Notes
-
mainfunction is the primary entry point -
Print to standard output:
print("Hello, World!") -
Datatypes (almost same as Java)
IntLongShortByteDoubleFloatStringCharBoolean
-
Variables and Constants
- Constants:
val <name> [: <type>] = <value> - Variables:
var <name> [: <type>] = <value>
- Constants:
-
Operators
- Logical:
&&|| - Bitwise:
andor - Equality:
===!==
- Logical:
-
Data Structures
- List:
val lst = listOf("a", "b", "c")List - Map:
val mp = mapOf("a" to 1, "b" to 2, "c" to 3)Map<String, Int> - Set:
val st = setOf("a", "b", "c")Set - Add
mutableas prefix for variables:val mutList = mutableListOf("a")
- List:
-
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
-
whenis like switch:when (x) { 1 -> print("1") 2 -> print("2") else -> print("None") }
-
-
Optional
- Use
?for nullable type:var x: String? = null - Use
?in call chain for safe calls:print(x?.length) - Use
!!to throw if null (like force unwrapx!in Swift):print(x!!.length) - Use
?:to get a default value (likex ?? <default>in Swift):print(x?.length ?: 0) - Use
as?for safe casting:val anInt: Int? = x as? Int
- Use
-
Class/Objects