fun main() {
var name = "Nina"
TakeIfTest().takeIf {
it.isGirl(name)
}?.doSomething(name)
name = "Tom"
TakeIfTest().takeIf {
it.isGirl(name)
}?.doSomething(name)
name = "Anna"
TakeIfTest().takeIf {
it.isGirl(name)
}?.doSomething(name)
}
class TakeIfTest {
fun doSomething(name: String) {
println(name)
}
fun isGirl(name: String): Boolean {
return when (name) {
"Jake" -> {
false
}
"Nina" -> {
true
}
"Anna" ->{
true
}
else -> {
false
}
}
}
}
运行结果: