# | Kotlin Koans |
---|---|
Kotlin Koans - Introduction | |
Kotlin Koans - Conventions | |
Kotlin Koans - Collections | |
Kotlin Koans - Properties | |
Kotlin Koans - Builders | |
Kotlin Koans - Generics |
Generic functions[ | ]
Kotlin
Copy
import java.util.*
fun <T, C: MutableCollection<T>> Collection<T>.partitionTo(first: C, second: C, predicate: (T) -> Boolean): Pair<C, C> {
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
fun partitionWordsAndLines() {
val (words, lines) = listOf("a", "a b", "c", "d e").
partitionTo(ArrayList<String>(), ArrayList()) { s -> !s.contains(" ") }
words == listOf("a", "c")
lines == listOf("a b", "d e")
}
fun partitionLettersAndOtherSymbols() {
val (letters, other) = setOf('a', '%', 'r', '}').
partitionTo(HashSet<Char>(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z'}
letters == setOf('a', 'r')
other == setOf('%', '}')
}
편집자 Jmnote Jmnote bot
로그인하시면 댓글을 쓸 수 있습니다.