Saranya Subramanian
Saranya Subramanian

Reputation: 461

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.

Upvotes: 2

Views: 15309

Answers (2)

Cililing
Cililing

Reputation: 4753

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.

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157437

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)

Upvotes: 3

Related Questions