Last active
October 18, 2018 10:21
-
-
Save Aracem/4496a536810aacdcc0e042e19679f0cf to your computer and use it in GitHub Desktop.
Elvis operator could not contains lambdas or several method calls, only 1 expresion. if var != null could not ensure unwrapping i.e. if var is a class property. These function extensions resolve these problems
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
package com.aracem.android | |
inline fun <T, K> T?.ifPresent(block: (T) -> K): K? { | |
return this?.let { block.invoke(it) } | |
} | |
inline fun <K> K?.orElse(block: () -> K): K { | |
return this?.let { it } ?: block.invoke() | |
} | |
class SampleClass { | |
var patatas: List<Patata>? | |
fun sampleMethod1(): Tortilla { | |
return patatas | |
.ifPresent(::makeTortilla) | |
.orElse(::makeFrenchTortilla) | |
} | |
fun makeTortilla(patatas: List<Patata>): Tortilla { | |
val cutPatatas = cutPatatas(patatas) | |
return makeTortilla(cutPatatas) | |
} | |
fun makeFrenchTortilla(): Tortilla { | |
val shackedEggs = shakeEggs() | |
return friedEggs(shackedEggs) | |
} | |
fun shampleMethod2(): Tortilla { | |
return patatas | |
.ifPresent { | |
// No lint warning on it nullability. | |
// Using if != null instead would produce a lint warning because | |
// patatas could be modified | |
}. orElse { | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment