고차함수
fun encodeMsg(msg: String, encode: (String) -> String): String {
return encode(msg)
}
encodeMsg 함수는 두 개의 매개변수를 받는다. 두 번째 매개변수 encode는 함수 타입이다.
문자열 msg와 함수 encode를 받아들이고, 문자열을 반환한다.
함수 내에서 encode 함수에 msg를 전달하고, encode 함수의 결과를 반환한다.
즉, msg를 encode 함수로 인코딩한 결과를 반환하는 것이 encodeMsg 함수의 역할이다.
fun enc2(input:String): String = input.reversed()
encodeMessage("abc", ::enc2)
val books = listOf("nature", "biology", "birds")
println(books.filter { it[0] == 'b' })
⇒ [biology, birds]
중괄호 {} 안의 필터 조건은 필터가 반복될 때 각 항목을 테스트한다.
표현식이 true를 반환하면 항목이 포함된다.
함수 리터럴에 매개변수가 하나만 있는 경우 해당 선언과 "->"를 생략할 수 있다.
매개변수는 it이라는 이름으로 암시적으로 선언된다.
val ints = listOf(1, 2, 3)
ints.filter { it > 0 }
// or ints.filter { n: Int -> n > 0 }
// or ints.filter { n -> n > 0 }
val instruments = listOf("viola", "cello", "violin")
val eager = instruments.filter { it [0] == 'v' }
println("eager: " + eager)
⇒ eager: [viola, violin]
val instruments = listOf("viola", "cello", "violin")
val filtered = instruments.asSequence().filter { it[0] == 'v'}
println("filtered: " + filtered)
⇒ filtered: kotlin.sequences.FilteringSequence@386cc1c4
시퀀스를 사용하면 필터링 조건이 충족될 때까지 요소를 하나씩 처리하여 불필요한 처리를 줄일 수 있다.
asSequence()와 함께 Sequence를 사용하여 필터를 평가한다.
현재 List가 아직 생성되지 않았고 정보만 가진 상태로 대기중이다.
만들어진 Sequence를 List로 바꾸기 위해서는 toList()를 사용해야한다.
val filtered = instruments.asSequence().filter { it[0] == 'v'}
⇒ new list: [viola, violin]
val numbers = setOf(1, 2, 3)
println(numbers.map { it * 3 })
=> [3, 6, 9]
val numberSets = listOf(setOf(1, 2, 3), setOf(4, 5), setOf(1, 2))
println(numberSets.flatten())
=> [1, 2, 3, 4, 5, 1, 2]