Hello community,
According to http://kotlinlang.org/docs/reference/null-safety.html
First, you can explicitly check if b
is null, and handle the two options separately:
val l = if (b != null) b.length() else -1
The compiler tracks the information about the check you performed, and allows the call to length()
inside the if. More complex conditions are supported as well:
Which seems to be working in the compiler
but not in the Kotlin IntelliJ IDEA Plugin
Is this issue already known?
I find it interesting.
fun handle(dataFields: Pair<String, Exception?>): List<Exception> {
val exceptions = linkedListOf<Exception>()
if (dataFields.second is Exception) {
exceptions.add(dataFields.second)
}
return exceptions
}
If I change `!= null` to `is Exception` (which should make more or less the same) IDEA tells me for the line `exceptions.add(dataFields.second)`
“Smart cast to ‘java.lang.Exception’ is impossible, because ‘dataFields.second’ could have changed since the is-check”
It seems this is no issue and the solution is either to add the as
cast or to introduce an intermedia local variable or to use the let()
extension function.
With extracted variable:
fun handle(dataFields: Pair<String, Exception?>): List<Exception> {
val exceptions = linkedListOf<Exception>()
val dataFieldException = dataFields.second
if (dataFieldException != null) {
exceptions.add(dataFieldException)
}
return exceptions
}
With `let()`:
fun handle(dataFields: Pair<String, Exception?>): List<Exception> {
val exceptions = linkedListOf<Exception>()
dataFields.second?.let { exceptions.add(it) }
return exceptions
}
What is a type of datenFelderPair and satzartenPair? It's important here, because smart cast support for properties is limited. E.g. at this moment it should not work for Pair<Something, Exception>.
types are
Pair<MutableSet<DatenFeld>, Exception?>
Pair<MutableSet<Satzart>, Exception?>
what I wanted to point out is that the IDEA Kotlin plugin marks it as an error if I ommit the type cast
while at the same time, if I add the typecast to get rid of the error Message in IDEA, I get a warning from the kotlin compiler that the cast is unecessary due to null safety checks:
And: Kotlin compiles fine without the “as Exception” typecast.