Reputation: 42
I have summary function that have two int parameters and a booelan paramater.
Here is my function
fun sum(s1:Int, s2:Int,str:Boolean = false) : Int{
if (str == false){
return s1+ s2
} else {
return (s1 + s2).toString()
}
}
this function returns of s1 + s2 but i have booelan paramater, if i set it to true ,my return will be s1 +s2.toString()
but i get error in toString how can i fix it
Upvotes: 1
Views: 100
Reputation: 8457
That is because the function return type is strictly an Int
. You may change that to Any
and it will compile fine but you won't have any type safety afterwards.
As far as I know kotlin doesn't have union types as other languages do like Typescript where you could do something like:
sum(a: number, b: number, str: boolean = false): number | string {
if (str == false){
return s1+ s2
} else {
return (s1 + s2).toString()
}
}
Upvotes: 2