Skip to content

Instantly share code, notes, and snippets.

@jaikeerthick
Last active February 20, 2024 13:43
Show Gist options
  • Save jaikeerthick/54a800e08559118890719d6f2d421d23 to your computer and use it in GitHub Desktop.
Save jaikeerthick/54a800e08559118890719d6f2d421d23 to your computer and use it in GitHub Desktop.
private inline fun <T1: Any, T2: Any, R: Any> safeLet(p1: T1?, p2: T2?, block: (T1, T2)->R?): R? {
return if (p1 != null && p2 != null) block(p1, p2) else null
}
@jaikeerthick
Copy link
Author

jaikeerthick commented Feb 20, 2024

safeLet{} is a convenient scope function that accepts two nullable parameters and execute the block() only if both parameters are not null

Usage:

fun main() {
    
    val name: String? = null
    val age: Number = 17
    
    safeLet(p1 = name, p2 = age){ _name, _age ->
        println("Person named: $_name and age $_age") // Will be printed only if name & age are not null
    }
    
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment