how to do type constraints in kotlin? like I would...
# announcements
i
how to do type constraints in kotlin? like I would like a value x only could have Int or String type?
a
Kotlin doenst have a union type i.e. Int|String how ever, if you want a function to take in an int or string, you can just overload the function
Copy code
fun Foo(i:Int) : Bar { . . .}

fun Foo(s:String) : Bar { . . .}
If you are designing an api that should return an
Int
or
String
you have to do some extra work, i.e.
Copy code
class Response<L,R>(val left:L,val right:R)

fun Foo(b:Bar):Response<Int,String> { . . .}
👍 4
m
excellent suggestion @andylamax I'd like to add that a sealed either type has my preference
Copy code
sealed class Either<out A, out B> {
    class Left<A>(val value: A): Either<A, Nothing>()
    class Right<B>(val value: B): Either<Nothing, B>()
}
so that you can do this (with an Either<String, Int> example)
Copy code
when(either){
    is Left -> doWithString(either.value)
    is Right -> doWithInt(either.value)
}
👆 1