Skip to content

Instantly share code, notes, and snippets.

@Aracem
Last active October 18, 2018 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aracem/4496a536810aacdcc0e042e19679f0cf to your computer and use it in GitHub Desktop.
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
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