Starting kotlin

1 minute read

Grammar

  • val : read only (like final)
  • var : Mutable
// 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

collections

val items = listOf("apple", "banana", "kiwi")
for (item in items) {
	println(item)
}

val items = setOf("apple", "banan", "kiwi")
  when {
  	"orange" in items -> println("juicy")
  	"apple" in items -> println("apple is fine too")
  }

val fruits = listOf("banana", "avocado", "apple", "kiwi")
  fruits.filter { it.startsWith"a") }
  		.sortedBy { it }
  		.map { it.toUpperCase() }
  		.forEach { println(it) }

function

fun sum(a: Int, b: Int): Int { return a + b }
fun sum(a: Int, b: Int) = a + b

Idioms, Generics

Samples

// case
var whenIssuedYn = "N"
if(rs.getString("when_issued_yn") == "Y" || symbol.endsWith(" WD")) whenIssuedYn = "Y"

Leave a comment