Alex Wilson
04/28/2020, 4:08 PMfun compose(f: (Int) -> Int, g: (Int) -> Int): (Int) -> Int = { f(g(it)) }
I understand this example.
The next step was to make the compose function polymorphic by using type parameters.
I'm having a hard time making sense of this.
Since they are all the same type of Int, I thought it would be just this:
fun <T> compose23Example(f: (T) -> T, g: (T) -> T): (T) -> T = { f(g(it)) }
The solution however is this:
fun <T, U, V> compose(f: (U) -> V, g: (T) -> U): (T) -> V = { f(g(it)) }
I've been looking at it and am having difficulty understanding exactly what I'm looking at. Can anyone help?Dominik wuttke
04/28/2020, 4:14 PMg()
and return any type you want. You can for example have an`Int` as variable for g()
and return a String
. The returntype of g()
is the type which f()
needs. f()
can now return any type you want. Your case is only correct when everything has the same type of variable, which is not always the case.molikuner
04/28/2020, 4:16 PMval myWeiredLength: (String) -> Int = compose<String, Int, Int>(f = { it + 1 }, g = { it.length })
That wouldn’t be possible with your solution.Casey Brooks
04/28/2020, 4:18 PMAlex Wilson
04/28/2020, 4:40 PMfun <T, U, V> compose(f: (U) -> V, g: (T) -> U): (T) -> V = { f(g(it)) }
A function called "compose" that returns a function that satisfies the signature (T) -> V
.
We're setting that return to a lambda of f(g(it))
.
Our method signature takes two parameters:
f:
a function with a parameter of type U
that transforms into a result into type V
g:
a function with a parameter of type T
that transforms into a result into into type U
V
represents f(g(it))
T
represents it
g
transforms T
to U
f
transforms U
to V