https://kotlinlang.org logo
Title
n

Nezteb

04/23/2019, 7:31 PM
Is there a builtin function to map a single argument to many functions that take that same argument? i.e.
val myArg = 1
val myFuncs = listOf(::addOne, ::addTwo, ::addThree)

myArg.someCoolMapFunctions(myFuncs)
There’s a stack overflow answer for Haskell to define this function yourself, but I don’t know what the equivalent Kotlin code would be https://stackoverflow.com/a/47501940/7682196
s

streetsofboston

04/23/2019, 7:32 PM
I don’t think Kotlin has this. What would the return type of
someCoolMapFunctions
be?
n

Nezteb

04/23/2019, 7:33 PM
ListType<myArg>
I would think
s

streetsofboston

04/23/2019, 7:33 PM
you mean
List<Int>
? or
List<() -> Int>
n

Nezteb

04/23/2019, 7:34 PM
List<Int>
in this case
what i’m doing for now is:
val listOfOutputs = listOf<Int>()
for(func in myFuncs) {
    listOfOutputs += func(myArg)
}
s

streetsofboston

04/23/2019, 7:36 PM
fun Int.someCoolMapFunctions(list: List<(Int)->Int>) : List<Int> = list.map { it(this) }
Or if you want to return a
List<() -> Int>
(a list of deferred results instead of a list of results):
fun Int.someCoolMapFunctions(list: List<(Int) -> Int>) : List<() -> Int> = list.map { { it(this) } }
r

Ruckus

04/23/2019, 7:44 PM
I don't see why you need it.
val outputs = myFuncs.map { it(myArg) }
is pretty concise.
👍 1
n

Nezteb

04/23/2019, 7:46 PM
Ohhhhhhhh. Neat! I didn’t realize you could do that with the regular
map
. Thanks!
👍 2