I'm trying to write a unit test for some Android code that looks for a specific key being present in an Intent
object. As part of my test, I'm creating an Intent
object and adding a String to it. However, when I use the below code, my variable is initalized to null:
val data = Intent().putExtra("key", "value")
// data is null
If I split this up into two lines, it works just fine:
val data = Intent()
data.putExtra("key", "value")
// data is non-null and contains my key/value
What feature of the Kotlin language is causing this to happen?
Note that putExtra()
returns an Intent
object. From the Android source:
public @NonNull Intent putExtra(String name, String value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putString(name, value);
return this;
}
In the first case, the inferred type is Intent!
. I was under the impression that this just means that it's an Intent
or an Intent?
but Kotlin doesn't want to make devs go crazy with Java platform types. Still, given that putExtra()
returns a non-null value, I'd expect the actual value of data
to be non-null.