Reputation: 23
I just recently started studying kotlin and when I changed Webrtc release to a newer one(1.0.22920) encountered following problem:
Type mismatch: inferred type is PeerConnection? but PeerConnection was expected
Here is the part of code where the error occurs:
val rtcConfig = PeerConnection.RTCConfiguration(iceServers)
peerConnection = peerConnectionFactory.createPeerConnection(rtcConfig, getPeerConnectionMediaConstraints(), videoPeerConnectionListener)
Most likely this is due to the fact that in the Webrtc library createPeerConnection became @Nullable:
@Nullable
public PeerConnection createPeerConnection(RTCConfiguration rtcConfig, MediaConstraints constraints, Observer observer) {
long nativeObserver = PeerConnection.createNativePeerConnectionObserver(observer);
if (nativeObserver == 0L) {
return null;
} else {
long nativePeerConnection = nativeCreatePeerConnection(this.nativeFactory, rtcConfig, constraints, nativeObserver);
return nativePeerConnection == 0L ? null : new PeerConnection(nativePeerConnection);
}
}
Attempt to put ? and !! in different places did not work.
I think that only my poor knowledge of kotlin separates me from solving the problem, can you help me?
Upvotes: 2
Views: 10743
Reputation: 28288
Since the method is nullable, this means it has a chance of returning null. This means you cannot declare it as a non-null PeerConnection
. You have three choices here:
PeerConnection?
- this means you accept nullable values!!
. At the end of the call to createPeerConnection
, add !!
. This throws an exception if it's null.?: [something to do here if it returns null without brackets]
after the call to createPeerConnection
.If you need PeerConnection to be non-null, I recommend you pick the last option. It's also a recommended option if you're checking for null, as:
var someNullableVar = getPossibleNull()
if(someNullableVar == null) someNullableVar = whatever();
is the same as:
var nonNullVar = getPossibleNull() ?: whatever()
You can also return and stop continued execution, but if you want to throw an exception, use !!
instead of the Elvis operator.
If you pick option #1 though, note that this means you'll have to do null checks on calls later.
Upvotes: 2
Reputation: 3655
Most probably because earlier you have declare the variable as not nullable:
var peerConnection: PeerConnection
And that means you cannot assign a @Nullable
value to that variable.
Change that to:
var peerConnection: PeerConnection?
Or you can force the value being returned to be non-null, (which I do not recommend) in which case:
peerConnection = peerConnectionFactory.createPeerConnection(rtcConfig, getPeerConnectionMediaConstraints(), videoPeerConnectionListener)!!
Notice the !!
at the end.
Upvotes: 3