Search

Kotlin Idiosm

Kotlin의 무작위적이고 자주 사용되는 관용어 모음

DTO(POJO/POCO) 생성

data class Customer(val name: String, val email: String)
Kotlin
복사
모든 속성에 대한 getter 제공 (var의 경우 setter 포함)
equals()
hashCode()
toString()
copy()
모든 속성에 대한 component1(), component2(), …

함수 매개변수의 기본값

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

컬렉션 필터링

val positives = list.filter { x -> x > 0 } val positives = list.filter { it > 0 }
Kotlin
복사

컬렉션 요소 확인

if ("john@example.com" in emailsList) { ... } if ("jane@example.com" !in emailsList) { ... }
Kotlin
복사

문자열 연결

println("Name $name")
Kotlin
복사
문자열 템플릿을 이용하여 연결

안전한 표준 입력

// Reads a string and returns null if the input can't be converted into an integer. For example: Hi there! val wrongInt = readln().toIntOrNull() println(wrongInt) // null // Reads a string that can be converted into an integer and returns an integer. For example: 13 val correctInt = readln().toIntOrNull() println(correctInt) // 13
Kotlin
복사
특정 타입으로 입력되지 않았다면 null을 반환

인스턴스 확인

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

읽기 전용 리스트

val list = listOf("a", "b", "c")
Kotlin
복사

읽기 전용 맵

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

맵 밸류 접근

println(map["key"]) map["key"] = value
Kotlin
복사

맵 또는 엔트리 탐색

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

범위 순회

for (i in 1..100) { ... } // closed-ended range: includes 100 for (i in 1..<100) { ... } // open-ended range: does not include 100 for (x in 2..10 step 2) { ... } for (x in 10 downTo 1) { ... } (1..10).forEach { ... }
Kotlin
복사

속성 지연 초기화

val p: String by lazy { // the value is computed only on first access // compute the string }
Kotlin
복사
속성에 최초로 접근할 때 본문 내용을 실행하여 초기화

확장 함수

fun String.spaceToCamelCase() { ... } "Convert this to camelcase".spaceToCamelCase()
Kotlin
복사
해당 클래스의 함수를 외부에서 확장하여 오버라이딩 할 수 있음

singleton 생성

object Resource { val name = "Name" }
Kotlin
복사
object 키워드를 붙이면 싱글턴 보장

inline value class

@JvmInline value class UserId(private val id: Int)
Kotlin
복사
성능 최적화, 타입 안전성, 명확한 의미 전달을 위해 value class를 inline으로 사용
@JvmInline을 붙여주면 컴파일 시에 객체를 인라인으로 처리해준다.

abstract class 인스턴스화

abstract class MyAbstractClass { abstract fun doSomething() abstract fun sleep() } fun main() { val myObject = object : MyAbstractClass() { override fun doSomething() { // ... } override fun sleep() { // ... } } myObject.doSomething() }
Kotlin
복사
추상 클래스 인스턴스화 시 추상 메서드들을 다 구현해야함

if-not-null 약어

val files = File("Test").listFiles() println(files?.size) // size is printed if files is not null
Kotlin
복사
변수명 뒤에 ? 키워드를 붙이면 해당 변수가 null이 아닌 경우 실행

if-not-null-else 약어

val files = File("Test").listFiles() // For simple fallback values: println(files?.size ?: "empty") // if files is null, this prints "empty" // To calculate a more complicated fallback value in a code block, use `run` val filesSize = files?.size ?: run { val someSize = getSomeSize() someSize * 2 } println(filesSize) // Execute a statement if null val values = ... val email = values["email"] ?: throw IllegalStateException("Email is missing!")
Kotlin
복사
변수명 뒤에 ? 키워드를 붙이고 ?: 키워드를 통해 해당 변수가 null이 아닌 경우 해당 메서드를 실행하고 null인 경우 ?: 뒤를 실행

빈 컬렉션 요소 가져오기

val emails = ... // might be empty val mainEmail = emails.firstOrNull() ?: ""
Kotlin
복사
firstOrNull(), lastOrNull() 특수 함수 존재
Elvis 연산자(?:)와 함께 사용하면 null인 경우 추가 작업 수행

let

// let 예제 val value = ... value?.let { ... // execute this block if not null } // let과 elvis 연산자를 이용한 mapping val value = ... val mapped = value?.let { transformValue(it) } ?: defaultValue // defaultValue is returned if the value or the transform result is null.
Kotlin
복사
null인 경우 let 키워드의 블럭을 실행
let과 Elvis 연산자를 사용하면 nullable한 값을 맵으로 변환할 수 있음

when

fun transform(color: String): Int { return when (color) { "Red" -> 0 "Green" -> 1 "Blue" -> 2 else -> throw IllegalArgumentException("Invalid color param value") } }
Kotlin
복사
when 문을 표현식 혹은 명령문으로 사용할 수 있다.
이를 통해 값을 반환할 수 있다.

try-catch

fun test() { val result = try { count() } catch (e: ArithmeticException) { throw IllegalStateException(e) } // Working with result }
Kotlin
복사

if

val y = if (x == 1) { "one" } else if (x == 2) { "two" } else { "other" }
Kotlin
복사