Consider a simple example in which smart casting doesn’t work.
class MyClass {
var name: String? = null
fun isNameEmpty(): Boolean {
return (name != null) && (name.isEmpty() || name.toLowerCase() == "empty")
}
}
Obviously smart casting doesn’t work in the latter part of the test and this code doesn’t compile.
One can solve this in various ways, for example with !!:
fun isNameEmpty(): Boolean {
return (name != null) && (name!!.isEmpty() || name!!.toLowerCase() == "empty")
}
but this is rather ugly - the non-null test is repeated useslessly:
Another solution using safe calls and Elvis operators:
fun isNameEmpty(): Boolean {
return (name != null) && (name?.isEmpty() ?: false || name?.toLowerCase() == "empty")
}
again not very pretty, optimized or readable.
The IMHO clearest and best solution is by defining a local variable for which the smart casts will work:
fun isNameEmpty(): Boolean {
val n = name
return (n != null) && (n.isEmpty() || n.toLowerCase() == "empty")
}
The improvement I suggest is to make this “local variable” solution available without actually spending a line of code defining the local variable.
The value that we test is dragged to the rest of the line (or the rest of the current scope) by appending a drag operator, say “>:” (but could be anything):
fun isNameEmpty(): Boolean {
return (name>: != null) && (name.isEmpty() || name.toLowerCase() == "empty")
}
The interpretation of this would be rigorously the same as in the code above with “val n = name”.
Another example:
fun fullName(): String {
if (name>: != null)
return "${name.toUpperCase()} $firstName"
else
return ""
}
would be rigorously identical to:
fun fullName(): String {
val n = name
if (n != null)
return "${n.toUpperCase()} $firstName"
else
return ""
}
Just having this kind of value dragging available for nullable properties of objects would be a huge benefit.
Note that the “drag operator” doesn’t break anything, it just provides a more concise way of writing the “local variable” solution.
It’s goal is similar to safe calls or the Elvis operator: code more efficiently, more concisely!
Looking forward to your feedback.