Something you should know about Kotlin

Chris Chen
2 min readAug 28, 2019
Photo from raywenderlich
  1. and && is a bit different in boolean check. For example:
val a = 3
val b = 4
val c = 5
val d = 3

val result1 = b == c && a == d

val result2 = (b == c) and (a == d)

You cannot write result2 to val result2 = b == c and a == d . Because operator precedence is not working for this case. It will look like val result2 = ((b == c) and a) == d . The difference between and && in boolean check is in result1 b == c so will not perform a == d check but result2 will check both. and operator is mainly the bitwise operators for integers. Same thing between or and ||

2. Destructuring Declarations

Let’s say we have data class Person

data class Person (
val name: String,
val age: Int = 0,
val gender: String = "male"
)

We can assign the value via destructure the data. The destructure is using the component to assign the values(in data class order of declaration).

val p = Person("Chris")
val (name1, age1) = p

System.out.println("$name1 $age1") //output:Chris 0

val (name2, age2, gender2) = Person("Mary", 18, "female")

System.out.println("$name2 $age2 $gender2") //output:Mary 18 female

if we don’t need name. Then we can do like

val (_, age3, gender3) = Person("Mary", 18, "female")

System.out.println("$age3 $gender3") //output:18 female

3. Function Overloading

Let’s say you have two functions in same name but one list in String and another one in Int. The IDE will shows same JVM signature error. But we still want to use the same name. Then we can add @JvmName to fix it.

fun updateList(dataInString: List<String>) { 
//do something
}

@JvmName("updateListInInt")
fun updateList(dataInInt: List<Int>) {
//do something
}

4. Create a map from pair

There is a method to easily transfer two types of value to pair.

public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)

So we can create a map like

val map = mapOf(1 to "a", 2 to "b", 3 to "c")

--

--