I am working through The Joy of Kotlin and came to this earlier today. Pages 61 and 62. `fun compos...
a
I am working through The Joy of Kotlin and came to this earlier today. Pages 61 and 62.
fun 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?
d
Your example would mean, that you can only enter 1 type, when you have an Int everything had to be an Int. What really happen is, that you can enter any type for the function
g()
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.
m
Theoretically your solution would work as well, as long as you only compose functions with the same type. So you could use your function to do the same thing as the example does with Int, but the actual “solution” is way more agile, as you can use multiple types there. Let me give an example:
Copy code
val myWeiredLength: (String) -> Int = compose<String, Int, Int>(f = { it + 1 }, g = { it.length })
That wouldn’t be possible with your solution.
c
Your solution is technically valid, but it only works for composing functions of a single type. There is no way for it to convert from one type to another. This example might help clear up the differences https://pl.kotl.in/fXK4lgQz4
a
Thank you! I can tell that I'm on the verge of understanding it, having moments of clarity, just waiting for the final picture. I'll chew on the examples you've all given. I appreciate you taking the time to respond!
👍 2
This make any sense?
fun <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
👍🏻 1