1. Define function
such as
fun sum(a: Int, b: Int): Int { return a + b }
If you do not need a return value, you can
fun printSum(a: Int, b: Int) { println("sum of $a and $b is $") }
2. Define variables
If it is a read-only variable, declare it with val; if it is a modifiable variable, declare it with var
val a: Int = 1 val b = 2 //Auto infer type 'Int' val c: Int //If there is no initial value, you need to provide the type c = 3 //Assign later var x = 5 //Auto infer type ` Int` x += 1
3. String template
var a = 1 // simple name in template: val s1 = "a is $a" a = 2 // arbitrary expression in template: val s2 = "$, but now is $a"
4. if expression
fun maxOf(a: Int, b: Int) = if (a > b) a else b
5. For a value that may be null, you must judge
fun parseInt(str: String): Int? { //If not int, return null } fun printProduct(arg1: String, arg2: String) { val x = parseInt(arg1) val y = parseInt(arg2) // Using `x * y` yields error because they may hold nulls. if (x != null && y != null) { // x and y are automatically cast to non-nullable after null check println(x * y) } else { println("either '$arg1' or '$arg2' is not a number") } }
6. Judge the object type with is keyword, which is equivalent to instanceOf java
fun getStringLength(obj: Any): Int? { if (obj !is String) return null // `obj` is automatically cast to `String` in this branch return obj.length }
7. List traversal
val items = listOf("apple", "banana", "kiwifruit") for (item in items) { println(item) } val items = listOf("apple", "banana", "kiwifruit") var index = 0 while (index < items.size) { println("item at $index is $") index++ }
fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" }
8, scope
val x = 10 val y = 9 if (x in 1..y+1) { println("fits in range") } val list = listOf("a", "b", "c") if (-1 !in 0..list.lastIndex) { println("-1 is out of range") } if (list.size !in list.indices) { println("list size is out of valid list indices range, too") } //ergodic for (x in 1..5) { print(x) } //step for (x in 1..10 step 2) { print(x) } println() for (x in 9 downTo 0 step 3) { print(x) }
9, set
for (item in items) { println(item) } when { "orange" in items -> println("juicy") "apple" in items -> println("apple is fine too") } //lambda expressions val fruits = listOf("banana", "avocado", "apple", "kiwifruit") fruits .filter { it.startsWith("a") } .sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) }
10, creating objects
val rectangle = Rectangle(5.0, 2.0) //'new' not required val triangle = Triangle(3.0, 4.0, 5.0)
References: https://kotlinlang.org/docs/reference/coding-conventions.html