Is there any trick for declare an extension ONLY f...
# announcements
d
Is there any trick for declare an extension ONLY for nullable type?
Copy code
class MyClass<T>

MyClass<String?>().myExtension()  // -> OK
MyClass<String >().myExtension()  // -> Does not compile?
d
What issue are you running into?
MyClass<String?>.myExtension()
should not be callable on a
MyClass<String>
object, unless you're using covariance. Or are you actually asking about
MyClass<String>?
?
d
I have
Copy code
interface Asserter<out T> {
    val actual: T?
}
and
Copy code
infix fun <T : Any?> Asserter<T>.`is`(_null: Null) =
    assertNull(actual)
and I’m expecting to NOT be able to call something like `assert that "Hello"
is
Null` ( where
assert that "Hello"
is
Asserter<String
)
z
I'm not sure if this would actually work (not at a computer rn) but I think you could create an overload of your function that has a non-nullable upper bound (
Any
) and give it a deprecated annotation with the error level (the coroutine library uses this trick to "capture" invalid calls and suggest alternatives), since the compiler will always select the most specific overload of a method. You also don't need the
Any?
bound in this code, it's the implicit upper bound if none is specified because it's the top type.
👍 2
d
Wow, seems cool 🙂 I’ll try! thanks!