skip to Main Content

I got error message:

AddAddressActivity.kt: (69, 53): Type mismatch: inferred type is String? but String was expected

enter image description here

2

Answers


  1. This is because the getString method returns a nullable value (String?) but you are assigning it to something that takes a non-null value (expects String). If you want to fix it you could assign it to a default string if it is null like this

    val villageId = getString("village_id") ?: "default"
    

    or to an empty string

    val villageId = getString("village_id").orEmpty()
    
    Login or Signup to reply.
  2. This is due to your villageId can be null which you have got from getString("village_id")

    for solving this you can use default value so when bundle don’t contains the provided key it will eventually returns the default value.

    val villageId = getString("village_id", "My Default Value")
    

    or you can use kotlin elvis to get other value when it’s null.

    val villageId = getString("village_id") ?: "My Default Value"
    

    or if you’re sure that intent will always contain the village id then you can use !!(not-null assertion operator) which will convert non-null value if not null else will throw exception

    val villageId: String = getString("village_id")!!
    

    you can more read about null safety in following link Null safety | Kotlin

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search