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)
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?
if
branch returns an int (i
),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){
//...
}