Zorome
Zorome

Reputation: 148

Kotlin. Expecting when-condition. How to fix?

I am writing a kotlin parser library and faced the following problem.

My code

fun main(args : Array<String>) {
val test = "jap"
val url = when (test) {
    "jap" -> "https://staticlib.me/manga-list?types[]=10",
    "cor" -> "https://staticlib.me/manga-list?types[]=11",
    "chi" -> "https://staticlib.me/manga-list?types[]=12",
    "eng" -> "https://staticlib.me/manga-list?types[]=13",
    "rus" -> "https://staticlib.me/manga-list?types[]=14",
    "fan" -> "https://staticlib.me/manga-list?types[]=15",
    "all" -> "https://staticlib.me/manga-list",
    else -> "https://staticlib.me/manga-list?types[]=10"
}
println(url)

}

Err message

compiler.kotlin:11:62: error: expecting a when-condition
    "jap" -> "https://staticlib.me/manga-list?types[]=10",
                                                         ^
compiler.kotlin:12:62: error: expecting a when-condition
    "cor" -> "https://staticlib.me/manga-list?types[]=11",
                                                         ^
etc.

how can i solve it?

Upvotes: 3

Views: 886

Answers (1)

Super-intelligent Shade
Super-intelligent Shade

Reputation: 6449

You have to remove commas inside the when expression:

fun main(args : Array<String>) {
    val test = "jap"
    val url = when (test) {
        "jap" -> "https://staticlib.me/manga-list?types[]=10"
        "cor" -> "https://staticlib.me/manga-list?types[]=11"
        "chi" -> "https://staticlib.me/manga-list?types[]=12"
        "eng" -> "https://staticlib.me/manga-list?types[]=13"
        "rus" -> "https://staticlib.me/manga-list?types[]=14"
        "fan" -> "https://staticlib.me/manga-list?types[]=15"
        "all" -> "https://staticlib.me/manga-list"
        else -> "https://staticlib.me/manga-list?types[]=10"
    }
    println(url)
}

You can also improve your code as follows:

fun main(args : Array<String>) {
    val test = "jap"
    var url = "https://staticlib.me/manga-list"
    if (test != "all") url += "?types[]=" + when (test) {
        "jap" -> "10"
        "cor" -> "11"
        "chi" -> "12"
        "eng" -> "13"
        "rus" -> "14"
        "fan" -> "15"
        else  -> "10"
    }
    println(url)
}

EDIT

As suggested by gidds in the comments, here is another way to improve the code:

fun main(args : Array<String>) {
    val test = "jap"
    val types = when (test) {
        "jap" -> "10"
        "cor" -> "11"
        "chi" -> "12"
        "eng" -> "13"
        "rus" -> "14"
        "fan" -> "15"
        "all" -> null
        else  -> "10"
    }
    val url = "https://staticlib.me/manga-list" + types?.let{ "?types[]=$it" }
    println(url)
}

Upvotes: 6

Related Questions