+ 1
Avoid smart cast hint in null checks
Is there anyway I can avoid the smart cast hint after the if in the example bellow? fun foo(): Any { val xpto = bar() if(xpto == null) { // do something fast and return } // do alot of stuff with xpto and return } fun bar(): Any?
1 Antwort
0
To avoid the smart cast hint, you can explicitly cast the result of bar() to Any before the if statement, like this:
fun foo(): Any {
val xpto: Any = bar() ?: return // do something fast and return
// do a lot of stuff with xpto and return
}
fun bar(): Any?
Alternatively, you can also use an if expression, like this:
fun foo(): Any {
return bar() ?: return // do something fast and return
// do a lot of stuff with bar() and return
}
fun bar(): Any?
By using either of these techniques, you can avoid the smart cast hint and also simplify your code.