Is their any way to create an extension function o...
# getting-started
j
Is their any way to create an extension function only available for nullable types? For example:
Copy code
fun Any?.assertNotNull(): Unit = TODO()

val nullable: String? = ""
val nonNullable: String = ""

nullable.assertNotNull() // works
nonNullable.assertNotNull() // works too
The last line makes no sense because the value cannot be
null
, but it compiles anyway. Is it possible to improve this?
e
String
can be transparently upcast into
String?
, just like how all types can be safely upcast into one of their parents
you could add a more specific overload and then mark it as an error,
Copy code
fun Any?.assertNotNull(): Unit = TODO()

@Deprecated("Non-nullable type", level = DeprecationLevel.ERROR)
@JvmName("assertNotNull!")
fun Any.assertNotNull(): {
    // no-op
}
1
j
alright, that's what I thought, no big deal anyway but I wanted to be sure, thank you!
g
You can also try to abuse `kotlin.internal.Exact`:
Copy code
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
fun <T: Any> @kotlin.internal.Exact T?.assertNotNull(): T = this ?: TODO()

fun main() {
    val nullable: String? = ""
    val nonNullable: String = ""

    nullable.assertNotNull() // works
    nonNullable.assertNotNull() // does not compile
}
j
Good to know! I will not use it since its internal but its really informative 😄