Migrating sure() (Kotlin M3 and Higher)

The sure() function is obsolete as of Kotlin M3. To remind you what it is, here’s the definition:

fun <T: Any> T?.sure() : T = 
    if (this != null) 
        this 
    else throw NullPointerException()

It asserts that the receiver expression is not equal to null. For example:

val a = f().sure() // we assert that f() will not return null here

This function has been replaced by the more concise ‘!!’ operator that does exactly the same thing:

val a = f()!!

If you have some old code that uses sure, you can

  • (Not recommended) Copy the definition given above to you project
  • Migrate your code using a quick-fix in IntelliJ Plugin for Kotlin M3

Suppose you have an unresolved ‘sure’ in your code. Invoke a quick-fix by pressing Alt+Enter on the error:

All unresolved calls to ‘sure()’ in you project will be migrated to ‘!!’ at once: