[英]Type mismatch: inferred type is String? but String was expected kotlin
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
).这是因为getString
方法返回一个可为空的值( String?
),但您将它分配给采用非空值(期望String
)的东西。 If you want to fix it you could assign it to a default string if it is null like this如果你想修复它,你可以将它分配给一个默认字符串,如果它是 null 像这样
val villageId = getString("village_id") ?: "default"
or to an empty string或空字符串
val villageId = getString("village_id").orEmpty()
This is due to your villageId
can be null which you have got from getString("village_id")
这是因为您的villageId
可以是您从getString("village_id")
获得的 null
for solving this you can use default value so when bundle don't contains the provided key it will eventually returns the default value.为了解决这个问题,您可以使用默认值,因此当 bundle 不包含提供的键时,它最终会返回默认值。
val villageId = getString("village_id", "My Default Value")
or you can use kotlin elvis to get other value when it's null.或者当它是 null 时,您可以使用 kotlin elvis 来获取其他值。
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或者如果您确定意图将始终包含村庄 ID,那么您可以使用 !!(非空断言运算符)如果不是 null 将转换非空值,否则将抛出异常
val villageId: String = getString("village_id")!!
you can more read about null safety in following link Null safety |您可以在以下链接Null 安全性中了解更多关于 null 安全性的信息 | Kotlin Kotlin
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.