user13125638
user13125638

Reputation: 97

Kotlin - Type mismatch: inferred type is Unit but Intent was expected

I'm very new to Kotlin and I'm getting an error stating Kotlin - Type mismatch: inferred type is Unit but Intent was expected and I'm unsure how to resolve this.

Any suggestions are appreciated.

Code Snippet:

  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)
    }

Note:

The error occurs on the line:

intent.data = Uri.parse(deeplinkURL)

Upvotes: 0

Views: 4963

Answers (2)

barkatme
barkatme

Reputation: 51

if condition is true, you don't return anything here simply add intent line right before else

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006724

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 you are going to assign a value to a variable or property from an if/else expression, you need both the if and the else branches to evaluate to the desired type. And, you do not need to provide the Uri to the Intent twice.

Upvotes: 2

Related Questions