[Kotlin Bootcamp] 3: Functions ② filters & lambdas

2020. 10. 17. 00:30개발공부/Kotlin

 

Kotlin Bootcamp : link

 

Kotlin Bootcamp for Programmers 3: Functions

There's a lot in this lesson, especially if you're new to lambdas. A later lesson revisits lambdas and higher-order functions. Note: You may have noticed that in Kotlin, as in some other languages, there is more than one correct way to do things. Making co

codelabs.developers.google.com

지난 글에선 default values와 function을 압축해 사용하는 방법을 배웠습니다. 이번 시간에는 좀 더 복잡하고 까다로운 개념인 filters와 lambdas라는 기능에 대해 배워보겠습니다. 

1) filters

코틀린의 filters는 list에 들어있는 정보들을 다룰 때 사용하는 기능입니다. 일례로 list에 들어있는 String  값들 중 첫 글자가 'p'로 시작하는 단어들을 반환시킬 때 아래와 같은 코드를 사용하면 됩니다.

val decorations = listOf ("rock", "pagoda", "plastic plant", "alligator", "flowerpot")

fun main() {
	println( decorations.filter {it[0] == 'p'})
}

그리고 lazy와 eager 방식의 filters 분류가 있는데요, 저에게 생소한 개념이라 찾아봤더니 결과값이 추가 명령없이 list 형태로 반환되는 방식이 eager 방식(default)고 접근을 해야지만 list가 생성되며 값이 반환되며 그 전까진 주소값으로만 처리되는 방식의 filters가 lazy 방식입니다. 따라서 바로 출력해 사용할 게 아니라면 메모리를 아끼는 lazy가 낫고, 즉시 값을 list로 꺼내야할 경우엔 eager 방식이 나아보입니다.

 - eager 방식 & lazy 방식의 filters

//eager 방식 filters

fun main() {
	val decorations = listOf ("rock", "pagoda", "plastic plant", "alligator", "flowerpot")
	val eager = decorations.filter {it[0] == 'p'}
    println( "eager: $eager")
}

//lazy 방식 filters

    val filtered = decorations.asSequence().filter { it[0] == 'p' }
    println("filtered: $filtered")
    
//lazy 방식을 리스트로 반환하는 명령문

    val newList = filtered.toList()
    println("new list: $newList")

이처럼 lazy를 사용한다면 변수로 받은 다음 toList() 메서드를 써주면 list 값이 반환됩니다. 뿐만 아니라 map 메서드를 사용해 map 형태로 출력할수도 있습니다.

2) lambdas

to be continued...

'개발공부 > Kotlin' 카테고리의 다른 글

[Kotlin Bootcamp] 3: Functions ①  (0) 2020.10.07