Kotlin-类型不匹配:推断的类型为Unit,但预期为Intent

时间:2020-03-27 19:29:33

标签: android kotlin

我对Kotlin还是很陌生,并且在声明Kotlin - Type mismatch: inferred type is Unit but Intent was expected时遇到错误,不确定如何解决此问题。

任何建议都值得赞赏。

代码段:

  val webURL: String? = dataMap["uri"]
    val intent: Intent
    intent = if (!webURL.isNullOrEmpty()) {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(webURL))
        intent.data = Uri.parse(webURL)
    } else {
        Intent(this, MainActivity::class.java)
    }

注意:

该错误发生在行上:

intent.data = Uri.parse(deeplinkURL)

2 个答案:

答案 0 :(得分:2)

val webURL: String? = dataMap["uri"]
val intent: Intent

intent = if (!webURL.isNullOrEmpty()) {
    Intent(Intent.ACTION_VIEW, Uri.parse(webURL))
} else {
    Intent(this, MainActivity::class.java)
}

如果要通过if / else表达式为变量或属性赋值,则需要同时使用ifelse分支来求值到所需的类型。并且,您无需两次向Uri提供Intent

答案 1 :(得分:0)

如果条件为真,则您在此处不返回任何内容 只需在其他位置之前添加intent