Want to define multiple variable let in Kotlin? If interested here are two of my functions for solving this.
1 2 3 4 5 6 7 8 9 10 11 12 13 | inline fun <T: Any> guardLet(vararg elements: T?, closure: () -> Nothing): List<T> { return if (elements.all { it != null }) { elements.filterNotNull() } else { closure() } } inline fun <T: Any> ifLet(vararg elements: T?, closure: (List<T>) -> Unit) { if (elements.all { it != null }) { closure(elements.filterNotNull()) } } |
Usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // Will print val (first, second, third) = guardLet("Hello", 3, Thing("Hello")) { return } println(first) println(second) println(third) // Will return val (first, second, third) = guardLet("Hello", null, Thing("Hello")) { return } println(first) println(second) println(third) // 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) } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.