GarseB010
GarseB010

Reputation: 27

using val in kotlin lambda

i'm playing around with map in kotlin, and currently I would like to see whether it would be possible to map a list of integers to a list of functions (Int) -> Int, while doing a bunch of operations inside the lambda that would require me to save values to vals

So I have this simple code:

val num = arrayOf(1, 2, 3, 4)

  val funcs = num.map <Int, (Int) -> Int > { x  -> {
        y -> y + x
    }}

This is a bit of a condensed example, the thing i'm really trying to do is a bit more convoluted. But I need to quite a bit of operations inside of of the 'inner' lambda, so I need to write codeblocks where I can use val. Like this:

val fs = num.map <Int, (Int) -> Int > { x  -> {
        y -> {
        val tmp = y *2
        val tmp1 = x / 2
        tmp + tmp1

        }
}}

But this part doesnt work, the compiler is confused by return types How can I do something like this?

Upvotes: 0

Views: 257

Answers (2)

AlexT
AlexT

Reputation: 2964

The reason your code in particular does not work is because you are adding an extra { after y -> in the second example:

val fs = num.map<Int, (Int) -> Int> { x ->
    { y ->
        { // this is not needed
            val tmp = y * 2
            val tmp1 = x / 2
            tmp + tmp1
            
        }// this is not needed
    }
}

So you are creating a "block" of {} which in kotlin means that you are creating a lambda function. The reason block is in quotes is because if you truly want a block in kotlin the syntax is run {}, as opposed to the java {}. But again, you do not need it here.

All you have to do is remove the extra brackets and your code is fine:

val fs = num.map <Int, (Int) -> Int > { x  -> {
        y ->
    val tmp = y *2
    val tmp1 = x / 2
    tmp + tmp1
}}

Upvotes: 2

IR42
IR42

Reputation: 9682

There is no difference between single-line and multi-line lambda

val fs = num.map { x ->
    { y: Int ->
        val tmp = y * 2
        val tmp1 = x / 2
        tmp + tmp1
    }
}

Upvotes: 1

Related Questions