Skip to content

Instantly share code, notes, and snippets.

@xiaofeidev
Created November 30, 2018 07:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiaofeidev/4e2ec679ca4f3b452da57aef3d3dc10d to your computer and use it in GitHub Desktop.
Save xiaofeidev/4e2ec679ca4f3b452da57aef3d3dc10d to your computer and use it in GitHub Desktop.
Boolean Extension, Say Goodbye to if-else expression
/**
* Created by xiaofei on 2018/11/30.
* desc:Boolean Extension, Say Goodbye to if-else expression
*/
sealed class BooleanExt<out T>//定义成协变
object Otherwise : BooleanExt<Nothing>()//Nothing是所有类型的子类型,协变的类继承关系和泛型参数类型继承关系一致
class TransferData<T>(val data: T) : BooleanExt<T>()//data只涉及到了只读的操作
//声明成inline函数
inline fun <T> Boolean.yes(block: () -> T): BooleanExt<T> = when {
this -> {
TransferData(block.invoke())
}
else -> Otherwise
}
inline fun <T> BooleanExt<T>.otherwise(block: () -> T): T = when (this) {
is Otherwise ->
block()
is TransferData ->
this.data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment