Skip to content

geekonjava/KotlinIdiom

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 

Repository files navigation

KotlinIdiom


type: doc layout: reference category: "Basics" title: "Idioms"

Idioms

A collection of random and frequently used idioms in Kotlin. If you have a favorite idiom, contribute it by sending a pull request.

Creating DTOs (POJOs/POCOs)

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

provides a Customer class with the following functionality:

  • getters (and setters in case of var{: .keyword }s) for all properties
  • equals()
  • hashCode()
  • toString()
  • copy()
  • component1(), component2(), ..., for all properties (see Data classes)

Default values for function parameters

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

Filtering a list

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

Or alternatively, even shorter:

val positives = list.filter { it > 0 }

String Interpolation

println("Name $name")

Instance Checks

when (x) {
    is Foo -> ...
    is Bar -> ...
    else   -> ...
}

Traversing a map/list of pairs

for ((k, v) in map) {
    println("$k -> $v")
}

k, v can be called anything.

Using ranges

for (i in 1..100) { ... }  // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }

Read-only list

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