// string interpolation
var a = 1
val s1 = "a is $a"
a = 2
val s2 = "${s1.replace('is', 'was')}, but now is $a"
// Condition
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
fun maxOf(a: Int, b: Int) = if (a>b) a else b
// null
var a: Int = 15
a = null // error
var b: Int? = null
b = null // success (? : nullable, !! : nullable is error)
// if abc is null, return null
fun abc(abc: ABC?): Int? {
// ...
return abc?.a
}
// java
for (int i = 1; i <= 5; i++) {
Log.i("TAG", "index : " + i);
}
// Kotlin
for (x in 1..5) {
println(x)
}
// Any keyword
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// 'obj' is automatically cast to 'String' int this branch
return obj.length
}
// 'obj' is still of type 'Any'
return null
}
// when with Any
fun main(args: Array<String>) {
cases("Hello") // String
cases(1) // Int
cases(System.currentTimeMillis()) // Long
cases(MyClass()) // Not a string
cases("hello") // Unknown
}
fun cases(obj: Any) {
when (obj) {
1 -> println("One")
"Hello" -> println("Greeting")
is Long -> println("Long")
!is String -> println("Not a string")
else -> println("Unknown")
}
}
// range
val array = arrayList<String>
array.add("aaa")
array.add("bbb")
val x = 3
if (x !in 0..array.size - 1)
println("Out: array size ${array.size} x = ${x}")
// Output
// Out: array size 2 x = 3
Leave a comment