Examine this code:
fun f(nullString: String?, nonNullString: String) {
nullString.ext() // Error: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
nullString.nullExt() // OK, nullabilities match
nonNullString.ext() // OK, nullabilities match
nonNullString.nullExt() // Expected error: nullExt is only applicable to String?
}
I would like to write two function signatures that makes the first and last function call not compile.
This makes the first line a compile error, but the last line still compiles:
fun String.ext(): Unit = TODO()
fun String?.nullExt(): Unit = TODO()
As far as I understand this works because "String extends String?", so defining an extension on String? is similar to defining one on CharSequence. Is there a way to prevent this from compiling?
A possible solution is to forbid the compiler to pick the "super" implementation, by declaring a more specific one:
Note:
String!will resolve toStringoverload.A real use case in case anyone is wondering:
we wouldn't want
somethingNonNull.orError()because in that caseorError()will never execute and therefore it is dead code.