Kotlin "own" null safety check


#1

I’m wondering is there a way how to say compiler that my “function” checks nullability ?

In following example

val label: String? = ""
            
if(!label.isNullOrBlank()) {
    label.length//complains as label type is nullable and has to be handled 
}

the null check is happenning in the isNullOrBlank so I’m sure it’s notnull,
but I want to avoid using !! or .let{}.
Anyway of doing it via annotation or somehow ?

Regards…


#2

You can do something like:

inline fun String?.unlessNullOrBlank(block: (String) -> Unit) {
    if (this != null && !isBlank())
        block(this)
}

and use it like:

label.unlessNullOrBlank {
        it.length
    }

#3

your code is the same as

val label: String? = ""
label?.takeIf{ it.notBlank() }?.length

I believe there are no ways to do it at the moment.
This like is a vote for this feature


#4

I think JB is working on an effects system that will do exactly what you want. https://github.com/JetBrains/kotlin/commit/b347e31fc41521bf3085cf066c35414bbd399f54