Boolean的扩展方法
class YesOrNo constructor(val reulst:Any?,val runOther:Boolean){
fun <T> otherwise(block:()->T):T = if (!runOther) reulst as T else block.invoke()
}
fun <T> Boolean.yes( block:()->T) = YesOrNo(if (this)block.invoke() else null,!this)
fun <T> Boolean.no( block:()->T) = YesOrNo(if (!this)block.invoke() else null,this)
inline fun Boolean.on(block:()->Unit) = OnOrOff(if (this){block.invoke();false} else true)
inline fun Boolean.off(block:()->Unit) = OnOrOff(if (!this){block.invoke();false} else true)
inline class OnOrOff constructor(val allowRunOtherwise:Boolean){
inline fun otherwise(block:()->Unit){ if (allowRunOtherwise)block.invoke()}
}
测试的代码
println("---true--")
true.on {
println("is true")
}.otherwise {
println("is false")
}
println("---true---")
true.off {
println("is false")
}.otherwise {
println("is true")
}
println("---true---")
println(true.yes {
"is true"
}.otherwise {
"is false"
}
)
println("---true---")
println(true.no {
"is false"
}.otherwise {
"is true"
}
)
println("---false--")
false.on {
println("is true")
}.otherwise {
println("is false")
}
println("---false---")
false.off {
println("is false")
}.otherwise {
println("is true")
}
println("---false---")
println(false.yes {
"is true"
}.otherwise {
"is false"
}
)
println("---false---")
println(false.no {
"is false"
}.otherwise {
"is true"
}
)
运行结果
---true--
is true
---true---
is true
---true---
is true
---true---
is true
---false--
is false
---false---
is false
---false---
is false
---false---
is false