Kotlin "own" null safety check

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…

1 Like

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
    }

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

I think JB is working on an effects system that will do exactly what you want. Effects: add facade of EffectSystem · JetBrains/kotlin@b347e31 · GitHub

1 Like