Search code examples
androidkotlinoperator-overloading

kotlin Why can't conditional control overload methods?


I think this should work in theory, and I've spent a lot of time doing so.

Here is an example of my code.

//code sample
fun sample(s1:String){
    //...
}

fun sample(i1:Int){
    //...
}

// I want to...

val str = "Hello"
val i = 00865

sample(if (str != "Hello") i else str)

Solution

  • Kotlin is a statically typed language; i.e., each expression must evaluate to a particular type at compile time (one and only one).

    sample(if (str != "Hello") i else str)

    Here, the conditional is an Expression in Kotlin, it should yield to a single type, but How?

    • The if branch returns an int (i),
    • The else branch returns a String (str).

    So, these are two different types; but the compiler is smart enough to consider both as of type Any giving you the warning:

    "Conditional branch result of type Int/String is implicitly cast to Any"

    Note that: Every Kotlin class has Any as a super class.

    But, that won't compile as well, because you don't have a sample method that takes in Any type.

    One way to fix this to have that overload version:

     fun sample(a: Any){
       //...
     }