개발/Kotlin
Kotlin에서 let을 여러번 쓰고 싶을 때
룬아님
2019. 9. 10. 15:42
kotlin으로 개발을 할때에
something?.let{}
이런 류의 코드를 많이 사용하게 된다.
그런데 변수 하나만 null 체크를 하는 것이 아니라 2개 이상 체크하고 싶으면 어떻게 해야할까?
하지만 Kotlin에서 직접적으로 지원하는 extension이 없기 때문에
https://stackoverflow.com/a/55736101
Multiple variable let in Kotlin
Is there any way to chain multiple lets for multiple nullable variables in kotlin? fun example(first: String?, second: String?) { first?.let { second?.let { // Do something...
stackoverflow.com
직접 util로 구현하여야 한다.
inline fun <T: Any> ifLet(vararg elements: T?, closure: (List<T>) -> Unit) {
if (elements.all { it != null }) {
closure(elements.filterNotNull())
}
}
// Will print
ifLet("Hello", "A", 9) {
(first, second, third) ->
println(first)
println(second)
println(third)
}
// Won't print
ifLet("Hello", 9, null) {
(first, second, third) ->
println(first)
println(second)
println(third)
}
반응형