Skip to content

Instantly share code, notes, and snippets.

@Makazy
Created May 23, 2020 17:28
Show Gist options
  • Save Makazy/f4030d16ee270ef664a0ff16ca17f0dc to your computer and use it in GitHub Desktop.
Save Makazy/f4030d16ee270ef664a0ff16ca17f0dc to your computer and use it in GitHub Desktop.
Kotlin withNotNull
withNoNulls("hello", "world", Throwable("error")) { p1, p2, p3 ->
p3.printStackTrace()
p1.plus(" ").plus(p2)
}?.let {
Log.d("TAG", it)
} ?: throw Exception("One or more parameters was null")
fun <R, A, B> withNotNull(p1: A?, p2: B?, function: (p1: A, p2: B) -> R): R? = p1?.let { p2?.let { function.invoke(p1, p2) } }
fun <R, A, B, C> withNotNull(p1: A?, p2: B?, p3: C?, function: (p1: A, p2: B, p3: C) -> R): R? = p1?.let { p2?.let { p3?.let { function.invoke(p1, p2, p3) } } }
fun <R, A, B, C, D> withNotNull(p1: A?, p2: B?, p3: C?, p4: D?, function: (p1: A, p2: B, p3: C, p4: D) -> R): R? = p1?.let { p2?.let { p3?.let { p4?.let { function.invoke(p1, p2, p3, p4) } } } }
fun <R, A, B, C, D, E> withNotNull(p1: A?, p2: B?, p3: C?, p4: D?, p5: E?, function: (p1: A, p2: B, p3: C, p4: D, p5: E) -> R): R? = p1?.let { p2?.let { p3?.let { p4?.let { p5?.let { function.invoke(p1, p2, p3, p4, p5) } } } } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment