"if" vs. "takeIf" in Kotlin? -
which of following 2 implementations better:
1.use "if"
fun f1(a: a?): r? { if (a != null) { val b = getb(a) if (b != null && b.f()) { val c = getc(b) if (c != null && c.f()) { return c.f2() } } } return null }
2.use "takeif" , "let"
fun f2(a: a?): r? = ?.let { getb(it) } ?.takeif { it.f() } ?.let { getc(it) } ?.takeif { it.f() } ?.let { it.f2() }
"takeif" , "let" better approach. though bit harder @ first experienced lambda expression find them full.
kotlin new language , 1 of advantage remove boilerplate code.
fun f2(a: a?): r? = ?.let { getb(it) } ?.takeif { it.f() } ?.let { getc(it) } ?.takeif { it.f() } ?.let { it.f2() }
this code snippet that. removed ugly 4 level nesting of if conditions.
hope helps.
Comments
Post a Comment