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
ephemient
06/08/2023, 9:29 PM
String
can be transparently upcast into
String?
, just like how all types can be safely upcast into one of their parents
ephemient
06/08/2023, 9:30 PM
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
Johann Pardanaud
06/08/2023, 9:32 PM
alright, that's what I thought, no big deal anyway but I wanted to be sure, thank you!
g
Gleb Minaev
06/09/2023, 7:43 AM
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
Johann Pardanaud
06/09/2023, 7:53 AM
Good to know! I will not use it since its internal but its really informative 😄