3

I am implementing an interface of a third party library(java). I am overriding a function with the following signature:

override fun onCallback(name: String?) {

}

I can change to the following without the compiler complaining:

override fun onCallback(name: String) {

}

What is the effect of this? What happens if the underlying library calls onCallback(null)?

Adam
  • 2,845
  • 2
  • 32
  • 46

1 Answers1

4

Types coming from Java are platform types (in this case, this parameter has a type of String!. If the parameter is not annotated in Java, it's up to you to decide whether it can ever have a null value, and you have to mark the type of the parameter in Kotlin accordingly. If you mark it as non-nullable, but Java code passes null to it, you'll get an exception at runtime - Kotlin generates checks for parameters like this, which you can look at by decompiling the generated bytecode.

Also see the official docs about null safety and platform types for more detail.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • Ahh ok, (I listened to a talk about platform types just the other week, my brain didn't connect) I guess I applied some wishful thinking; i kinda hoped calls not matching the function would just be filtered away into the nothingness... Don't see how I can avoid the nullcheck now -.-' – Adam Nov 24 '17 at 21:11
  • If you want do that, you could make the parameter have a nullable type and then add `name ?: return` as the first line of the function. Since parameters are essentially `val`s , it would be smart cast to the non-nullable type for the rest of the function. – zsmb13 Nov 25 '17 at 07:15