Created
May 25, 2019 06:44
-
-
Save itmammoth/57f25b89d24800c27ebb556690f818d1 to your computer and use it in GitHub Desktop.
[Kotlin] Unwrap null objects or return immediately
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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