Skip to content

Instantly share code, notes, and snippets.

@itmammoth
Created May 25, 2019 06:44
Show Gist options
  • Save itmammoth/57f25b89d24800c27ebb556690f818d1 to your computer and use it in GitHub Desktop.
Save itmammoth/57f25b89d24800c27ebb556690f818d1 to your computer and use it in GitHub Desktop.
[Kotlin] Unwrap null objects or return immediately
fun <T1, T2> safe(t1: T1?, t2: T2?): Pair<T1, T2>? {
return if (t1 == null || t2 == null) null else Pair(t1, t2)
}
fun <T1, T2, T3> safe(t1: T1?, t2: T2?, t3: T3): Triple<T1, T2, T3>? {
return if (t1 == null || t2 == null || t3 == null) null else Triple(t1, t2, t3)
}
// Usage (case in fragments)
val (context, activity) = safe(context, activity) ?: return
val (context, activity, view) = safe(context, activity, view) ?: return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment