Raghul G
Raghul G

Reputation: 7

Kotlin - Issue with Elvis operator

Why the below code gives error? It should print "Bonjour" as output

 fun main()
{

    var a:String? = null
    var b:String? = "Hello"

    var result1 = a?:"Gracias"
    var result2 = b?:"Bonjour"
    println(result2)
}

Upvotes: -2

Views: 63

Answers (1)

Tenfour04
Tenfour04

Reputation: 93511

b?:"Bonjour" means, “if b is not null, then whatever b is, but if it’s null, then "Bonjour". Since b is not null, it evaluates to what b is, which is "Hello".

By the way, the term “error” in the programming world means the code will not compile, not that it’s giving you unexpected results when you run it.

Upvotes: 1

Related Questions