Hi! I want to do something if a `java.io.File` var...
# getting-started
t
Hi! I want to do something if a
java.io.File
variable is null or not readable. In Java this vould be
Copy code
if (myFile == null || !myFile.canRead()) {
    // error!
}
which works always because of short-circuit evaluation. IntelliJ translates the above code to:
Copy code
if (simDesc == null || !simDesc!!.canRead()) {
    // error!
}
which is a bit ugly IMHO. Any idea on making it more idiomatic?
k
thecipster: it seems
simDesc
is not a local variable but a mutable property. either save the value to a local variable, make the property immutable (
val
) or use some tricks like
simDesc.takeIf { it.canRead() }?.let { /* do stuff */ }
u
I kinda feel like the current state of dealing with
Boolean
returning methods/properties on nullable objects is not very satisfying
👍 1
t
@kirillrakhman, @uhe thanks for the reply. Unfortunately
simDesc
must be a mutable property (
var simDesc: File? = null
) because Java library. The trick with
takeIf
is nice but hardly more readable 🙂. I think that in this case the compiler knows enough to avoid the
!!
operator.
u
you can't avoid it. it's perfectly possible that
simDesc
is null on the second branch
k
it could be set to null on a different thread
like I said, you can save the value to a local variable
t
OK now i see it, i wasn't considering multithreading issues
k
also you can do
if (simDesc?.canRead() != true)
but that won't help you, if you need to access the value again
t
I just tried with copying to a local variable and indeed the compiler is smart enough to consider short-circuit evaluation and removes the
!!
. Thanks a lot! 👍
k
you can read up on smart casts here: https://kotlinlang.org/docs/reference/typecasts.html