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.
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)!!