lifter
08/30/2018, 3:09 PMjustAddThem1
such that it takes any numeric type?
justAddThem2
and justAddThem3
won't compile.
fun justAddThem1(x: Int, y: Int) = x + y
fun justAddThem2(x: Number, y: Number) = x + y
fun <T : Number> justAddThem3(x: T, y: T) = x + y
Andreas Sinz
08/30/2018, 3:10 PMfun <T: Number> justAddThem(x: T, y: T, f: (T, T) -> T) = f(x, y)
Can Orhan
08/30/2018, 3:11 PMAndreas Sinz
08/30/2018, 3:12 PMCan Orhan
08/30/2018, 3:12 PMcedric
08/30/2018, 3:13 PMlifter
08/30/2018, 3:18 PMfun <T> f(x: T) { /* ... */ }
Function f
is parametrically polymorphic.
Ad-hoc polymorphism in Haskell would be when there is a typeclass constraint on the type variable. Haskell typeclasses are similar to OOP interfaces. So, in Kotlin, I'd imagine something like this:
fun <T: Comparable> f(x: T) { /* ... */ }
T
is constrained in the sense that it's no longer anything under the sun, it's anything that is comparable.cedric
08/30/2018, 3:23 PMlifter
08/30/2018, 3:25 PMfun <T: Number> justAddThem(x: T, y: T, f: (T, T) -> T) = f(x, y)
really doesn't add the numbers, does it? Looks like it just takes two numbers and a function, and applies the function to the two numbers.cedric
08/30/2018, 3:30 PMlifter
08/30/2018, 3:32 PMf
could do anything.fun f(x: Int, y: Int) { println("$x / $y") }
justAddThem
to "add" or "combine" in some sense, but there are no guarantees from the type system or otherwise that enforce that.Andreas Sinz
08/30/2018, 3:57 PMfun <T: Number> justAddThem(x: T, y: T): T {
return when {
x is Int && y is Int -> x + y
x is Double && y is Double -> x + y
[...]
else -> throw Exception()
} as T
}
lifter
08/30/2018, 3:59 PM&& y is Int
if x
and y
are both T
.Andreas Sinz
08/30/2018, 4:01 PM