Created
November 30, 2018 07:09
-
-
Save xiaofeidev/4e2ec679ca4f3b452da57aef3d3dc10d to your computer and use it in GitHub Desktop.
Boolean Extension, Say Goodbye to if-else expression
This file contains hidden or 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
/** | |
* 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