I have a piece of code:
class Test {
fun test() {
val fruit = if (Apple().doSomeThing() != null) {//1
val result = Apple().doSomeThing() //2
//...use result
} else if (Banana().doSomeThing() != null) {
Banana().doSomeThing()
} else {
Peach().doSomeThing()
}
}
internal open class Fruit
internal class Apple : Fruit() {
fun doSomeThing(): Boolean? {
return false
}
}
internal class Banana : Fruit() {
fun doSomeThing(): Boolean? {
return false
}
}
internal class Peach : Fruit() {
fun doSomeThing(): Boolean? {
return false
}
}
}
It call Apple().doSomeThing() twice, can i declare a variable in if statement like this:?
var result :Boolean? = null
if((result = Apple().doSomeThing()) != null){
//result.xxxx //use result directly
}
And,how can i write test() method more gracefully!!