[Kotlin] Kotlin Idioms - 4

Kotlin Idioms 배우기 - 4

참고 사이트

  • 본 포스팅은 많은 부분들이 생략되어있습니다.

Create DTOs (POJOs/POCOs)

1
data class Customer(val name: String, val email: String)

provides

  • getters (and setters in case of var)
  • equals()
  • hashCode()
  • toString()
  • copy()
  • component1(), component2(), …

Default values for function parameters

1
fun foo(a: Int = 0, b: String = "") { ... }

Filter a list

1
val positives = list.filter { x -> x > 0}

or

1
val positives = list.filter { it > 0 }

Check the presence of an element in a collection

1
2
if ("john@example.com" in emailsList) { ... }
if ("jane@example.com" !in emailsList) { ... }

String interpolation

1
println("Name $name")

Instance checks

1
2
3
4
5
when (x) {
    is Foo -> ...
    is Bar -> ...
    else   -> ...
}

Read-only list

1
val list = listOf("a", "b", "c")

Read-only map

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

Access a map entry

1
2
println(map["key"])
map["key"] = value

Traverse a map or a list of pairs

1
2
3
4
// k, v는 자유로운 이름으로 사용 가능합니다.
for ((k, v) in map) {
    println("$k -> $v")
}

Iterate over a range

1
2
3
4
5
for (i in 1..100) { ... } // include 100
for (i in 1 until 100) { ... } // exclude 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }

Lazy property

1
2
3
val p: String by lazy {
    // compute the string
}

Extension functions

1
2
3
fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()

Create a singleton

1
2
3
object Resource {
    val name = "Name"
}