Inline fun null checks?


#1

Given this:

inline fun String?.isNotNull() : Boolean = this != null

We get…

 private fun test() {
     val test = someCallThatCanReturnANullString();

     if (test != null) {
        test.replaceFirst("hmm", "it works!")
     }

     if (test.isNotNull()) {
        test.replaceFirst("hmm", "Nope! Compiler error despite the inline fun!")
     }
 }

I’m new to Kotlin and perhaps missing something but I would expect that given this is an inline fun and thus can’t be runtime replaced, it should be possible for the compiler to determine that test is safely null checked. Is this a limitation of the compiler? Is there a reason why it shouldn’t recognize this?


#2

Yes, this is a limitation of the compiler, mostly caused by performance considerations.


#3

See also https://youtrack.jetbrains.com/issue/KT-14397


#4

Thanks for the info guys


#5

I realize this is made up code, so my suggestions may not be relevant to your specific scenario.

As you have stated you are new to Kotlin, perhaps you didn’t consider the following options.

If I put your code in Intellij, it automatically suggest the following:

test?.replaceFirst("hmm", "it works!")

Other alternatives are below depending on what you want to achieve.

test?.let {
    test.replaceFirst("hmm", "it works!")
}

test?.with {
   replaceFirst("hmm", "it works!")
}

HTH