https://kotlinlang.org logo
#functional
Title
# functional
n

Niels Renard

07/12/2018, 7:02 AM
want to have something like fun funGenerator(some flags) { if flag = a return fn(param) { some operation on param } if flag = b return fn(param1 param2} {some different operations } }
g

gildor

07/12/2018, 7:03 AM
first of all define return type, as I mentioned in another thread, also, usually easier to use lambda instead of anonymous function
hah, funny, actually, for your case anonymous function is just fine, because do not clash with
when
block:
Copy code
fun funGenerator(flag: Int): () -> Unit {
        return when (flag) {
            1 -> fun() { /* Do something for flag 1 */ }
            2 -> fun() { /* Do something for flag 1 */ }
            else -> error("Unknown flag")
        }
    }
n

Niels Renard

07/12/2018, 7:07 AM
That's exactly the kind of stuff I'm trying to move out of a different function. Thanks, I can work with this
Thought Unit was just for returning void
g

gildor

07/12/2018, 7:09 AM
Kotlin doesn’ have
void
, so yeah, use Unit or any type which this function should return
you also can use lambdas instead, anonymous function is very rare thing on my practice
p

pakoito

07/12/2018, 9:20 AM
are local functions expressions?
or statements
g

gildor

07/12/2018, 9:24 AM
Expressions. Local anonymous function is almost the same as lambda, the biggest difference is that you can use return inside of anonymous function
p

pakoito

07/12/2018, 9:25 AM
yeah they get compiled as lambdas, I didn’t know you could also assign them to a variable. We JS, guise.
n

Niels Renard

07/12/2018, 11:43 AM
ended up rewriting them as lambda's. lot cleaner
4 Views