简体   繁体   中英

Type mismatch: inferred type is Context? but Context was expected - Kotlin

I am getting above mentioned issue after updating kotlin version to 1.3.0

Below is the code,

     public class SequenceLayout(context: Context?, attrs: AttributeSet?, defStyleAttr: Int)
: FrameLayout(context, attrs, defStyleAttr), ViewTreeObserver.OnGlobalLayoutListener {

}

First line I am getting that. issue . Pls help me to solve this.

The signature is wrong. Context can't be null to create the view, while AttributeSet can. Change it like

 public class SequenceLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int)

In Kotlin Type is different type than Type? . The second one is Nullable. To first one you cannot assign null value.

Whenever you expect Type? you can use Type , but there is no way to use it in opposite way.

This way Kotlin ensure null safety. More you can read here: https://kotlinlang.org/docs/reference/null-safety.html

So, how to solve your problem?:

  • Use !! operator - this operator will convert nullable type to notnullable, but, if value is null you'll get NullPointerException

  • Change signature of your function to use compatible types. In your case this looks like proper way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM