简体   繁体   English

类型不匹配:推断类型是字符串? 但预计字符串 kotlin

[英]Type mismatch: inferred type is String? but String was expected kotlin

I got error message:我收到错误消息:

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

在此处输入图像描述

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.

相关问题 类型不匹配:推断类型是String,但是在kotlin中预计会出现Charset - Type mismatch: inferred type is String but Charset was expected in kotlin 类型不匹配:推断类型为 String 但预期为 Int,Kotlin - Type mismatch: inferred type is String but Int was expected , Kotlin 类型不匹配:推断的类型是String? 但是字符串是预期的 - Type mismatch: inferred type is String? but String was expected 错误:(29, 34) 类型不匹配:推断的类型是字符串? 但可编辑! 预料之中 - Error:(29, 34) Type mismatch: inferred type is String? but Editable! was expected 错误类型不匹配:推断类型是 View! 但字符串是预期的 - Error Type mismatch: inferred type is View! but String was expected Kotlin推断出类型不匹配 - Kotlin inferred type mismatch 类型不匹配:推断的类型是上下文? 但希望有上下文-Kotlin - Type mismatch: inferred type is Context? but Context was expected - Kotlin Kotlin:类型不匹配:推断的类型是 Intent? 但意图是预期的 - Kotlin : Type mismatch: inferred type is Intent? but Intent was expected Kotlin - 类型不匹配:推断的类型是 Unit,但 Intent 是预期的 - Kotlin - Type mismatch: inferred type is Unit but Intent was expected Kotlin类型不匹配:推断类型是View! 但TextView是预料之中的 - Kotlin Type mismatch: inferred type is View! but TextView was expected
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM