Reputation: 3165
I know that this is a very simple error but I can't quite comprehend the nuances of kotlin enough to solve it just yet.
I'm getting the error:
Type mismatch: inferred type is BluetoothDevice? but BluetoothDevice was expected
When trying to pass a BluetoothDevice
in as parcelable
class ScanDevice(var device: BluetoothDevice, var rssi: Int): Parcelable {
...
constructor(parcel: Parcel) : this(
parcel.readParcelable(BluetoothDevice::class.java.classLoader), <--- here
parcel.readInt()
)
...
It's technically just a warning and not actually an error but I'm not sure what is happening here.
Upvotes: 0
Views: 1897
Reputation: 33
Instead of using !! it would probably be better to to perform a null safe call like this.
parcel?.let{
it.readParcelable(BluetoothDevice::class.java.classLoader)
it.readInt()
}
This only executes the code when parcel is not null. Only use !!
when you are 100% sure that variable/object is not null.
Upvotes: 1
Reputation: 54204
The documentation for Parcel.readerParcelable()
says:
Returns the newly created
Parcelable
, ornull
if a null object has been written.
This means that, if we were living in Kotlin world, the return type of Parcel.readParcelable()
would be T?
and not T
(i.e. it would be nullable).
Since you are in control of the writing, you know that it won't return null. That means that you're safe to convert the result to a non-nullable type by using the !!
operator:
parcel.readParcelable(BluetoothDevice::class.java.classLoader)!!
Upvotes: 2
Reputation: 134664
This is because Parcel.readParcelable
is nullable. If the Parcel
had previously had a null value written to it at that position, null would be returned. In your case, if you can guarantee that you are never writing null to the Parcel
, you can simply assert that the value is not null:
constructor(parcel: Parcel) : this(
parcel.readParcelable(BluetoothDevice::class.java.classLoader)!!,
parcel.readInt()
)
This would crash at runtime if a null value were written to the Parcel
.
Upvotes: 1