EDIT: There were some issues with the original idea. So I have thought of a better idea.
The keyword ‘abort’ should abort the method, it is nested in. For example:
val v1 = 0 as Int? val v2 = 1337 as Int? val v3 = 7331 as Int? println(maxOf( v1 ?: abort null, v2 ?: abort, // abort if value is null, if the funcion returns unit, then don't return anything, else return null v3 ?: abort )) // prints null
This method is more verbose, and people wouldn’t overread it. If a programmer sees this kind of code, then it would be easy to understand, that it is a new feature, and could just google it. It would then also support labeled “breaks”, which would be very convenient, e. g.
val v1 = 0 as Int? val v2 = 1337 as Int? val v3 = 7331 as Int? println(maxOf( v1 ?: abort@println null, v2 ?: abort@println, v3 ?: abort@println ))
Original idea starting here:
This is a small suggestion that would help me a lot. This Code doesn’t work because maxOf doesn’t accept nullable values.
val v1 = 5 as Int? val v2 = 4 as Int? val v3 = 6 as Int? val v4 = 1 as Int? println(maxOf(v1, v2)) println(minOf(v3, v4))
This would be fixable by using if statements like this, but this is ugly and not really modern (like Kotlin should be)
val v1 = 5 as Int? val v2 = 4 as Int? val v3 = 6 as Int? val v4 = 1 as Int? if(v1 != null && v2 != null) println(maxOf(v1, v2)) if(v3 != null && v4 != null) println(minOf(v3, v4))
If those were fields, then it would be even more complicated. But luckily there is the ?: return operator. So the following code works fine, BUT if i change any of those 4 values to null, main would return and not continue at all.
var v1 = 5 as Int? // Would not work as intended if v1 was null. var v2 = 4 as Int? var v3 = 6 as Int? var v4 = 1 as Int? fun main() { println(maxOf(v1 ?: return, v2 ?: return)) println(minOf(v3 ?: return, v4 ?: return)) }
The following code works as expected, but is just ugly as hell.
var v1 = 5 as Int? var v2 = 4 as Int? var v3 = 6 as Int? var v4 = 1 as Int? fun main() { v1?.let { v1n -> v2?.let { v2n -> println(maxOf(v1n, v2n)) } } v3?.let { v3n -> v4?.let { v4n -> println(minOf(v3n, v4n)) } } }
So this is my final suggestion. The using ? on a nullable object in a function should just don’t execute the function. Alternatively something like ?: exit would also work.
var v1 = 5 as Int? var v2 = 4 as Int? var v3 = 6 as Int? var v4 = 1 as Int? fun main() { println(maxOf(v1?, v2?)?) println(minOf(v3?, v4?)?) }