Kotlin - Issue with Elvis operator

35 Views Asked by At

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

There are 1 best solutions below

2
Tenfour04 On

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.