Reputation: 71
I got error message:
AddAddressActivity.kt: (69, 53): Type mismatch: inferred type is String? but String was expected
Upvotes: 2
Views: 19666
Reputation: 667
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
Upvotes: 1
Reputation: 10940
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()
Upvotes: 6