Kotlin Koans - Introduction

Jmnote (토론 | 기여)님의 2019년 3월 28일 (목) 01:09 판 (→‎Lambdas)

1 개요

2 Hello, world!

fun start(): String = "OK"

3 Named arguments

fun joinOptions(options: Collection<String>) = options.joinToString(", ","[","]")

4 Default arguments

fun foo(name: String, number: Int=42, toUpperCase: Boolean=false) =
        (if (toUpperCase) name.toUpperCase() else name) + number

fun useFoo() = listOf(
        foo("a"),
        foo("b", number = 1),
        foo("c", toUpperCase = true),
        foo(name = "d", number = 2, toUpperCase = true)
)

5 Lambdas

fun containsEven(collection: Collection<Int>): Boolean = collection.any { it % 2 == 0 }

6 Strings

val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"

fun getPattern(): String = """\d{2} ${month} \d{4}"""

7 Data classes

data class Person(val name: String, val age: Int)

fun getPeople(): List<Person> {
    return listOf(Person("Alice", 29), Person("Bob", 31))
}

8 Nullable types

fun sendMessageToClient(
        client: Client?, message: String?, mailer: Mailer
){
    val email = client?.personalInfo?.email
    if (email != null && message != null) 
        mailer.sendMessage(email, message)
}

class Client (val personalInfo: PersonalInfo?)
class PersonalInfo (val email: String?)
interface Mailer {
    fun sendMessage(email: String, message: String)
}

9 Smart casts

fun eval(expr: Expr): Int =
        when (expr) {
            is Num -> expr.value
            is Sum -> eval(expr.left) + eval(expr.right)
            else -> throw IllegalArgumentException("Unknown expression")
        }

interface Expr
class Num(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr

10 Extension functions

fun Int.r(): RationalNumber = RationalNumber(this, 1)
fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(first, second)

data class RationalNumber(val numerator: Int, val denominator: Int)

11 Object expressions

12 SAM conversions

13 Extensions on collections

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}