//===================================================================
//
// BooleanExt
//
//===================================================================
//T的子类
sealed class BooleanExt<out T> constructor(val boolean: Boolean)
object Otherwise : BooleanExt<Nothing>(true)
class WithData<out T>(val data: T) : BooleanExt<T>(false)
inline fun <T> Boolean.yes(block: () -> T): BooleanExt<T> = when {
this -> {
WithData(block())
}
else -> Otherwise
}
inline fun <T> Boolean.no(block: () -> T) = when {
this -> Otherwise
else -> {
WithData(block())
}
}
inline infix fun <T> BooleanExt<T>.otherwise(block: () -> T): T = when (this) {
is Otherwise -> block()
is WithData<T> -> this.data
}
inline operator fun <T> Boolean.invoke(block: () -> T) = yes(block)
//===============================================================================
fun main() {
false.yes {
println("=======================yes")
}.otherwise {
println("=======================otherwise") //
}
false.no {
println("=======================no") //
} otherwise {
println("=======================otherwise")
}
true.yes {
println("=======================yes") //
}.otherwise {
println("=======================otherwise")
}
true.no {
println("=======================no")
} otherwise {
println("=======================otherwise") //
}
}
kotlin : BooleanExt
最新推荐文章于 2023-12-01 09:40:06 发布