Is there any way to limit function/method signatur...
# announcements
h
Is there any way to limit function/method signature to specific types as fun function(x:String|Int) ?
k
Kotlin doens't have union types, but you can either create your own boilerplaty union types with sealed classes, or if it's just a function you can create overloads.
h
Yes, I know both of them, just wanted to be sure. BTW, are there any plan to add DU in Kotlin?
k
DU being? Union types?
h
Yes, I know os sealed class but recently I encounter in Exposed signature of x:Any? with two types and error
I found it pretty nasty 🙂
k
Are you asking if there are plans to add union types to Kotlin?
h
Yes
k
If so, I don't think so, @yole was't that positive about them here: https://discuss.kotlinlang.org/t/union-types/77/2
Your case of a function can be solved with overloads though, so I don't really see a problem?
h
Yes, but what about hairy signature like this (some:String|Int, val1: Int, val2:String, val3: Int)
k
Copy code
fun foo(some: String, val1: Int, val2: String, val3: Int) { ... }
fun foo(some: Int, val1: Int, val2: String, val3: Int) { ... }
h
I know. And now please introduce parameter val4 supposing you have 3 or 4 overloadings
Pretty painful, right? Or do I miss something?
k
That's going to be a bit of work, yes.
h
🙂
i
@hanpari Discriminated unions are in fact sealed classes and they are already in Kotlin.
k
What's the difference between discriminated and other union types?
i
https://en.wikipedia.org/wiki/Tagged_union Each variant of such union is tagged, so given a value of such union you can always determine which variant is that.
👍 1
h
@ilya.gorbunov As I have already explained the way Kotlin implementing sealed class is no big help in function signature. Even in Exposed, made by Jetbrains, I saw used Any to have choice from two types. When the type didnt match it throw Error
The overloading of function is actually closer to what I had on my mind. But this is bothersome when you have alot of overloadings and lot of parameters
g
I would use overloading of function, but if I really have such complicated case (which is not really common on my practice) with multiple params that could have different type I would just use Sealed class. It’s not free, one more wrapper, but easy to use and already supported by the language