0

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?

6
  • what part doesn't work? Commented Apr 17, 2021 at 22:00
  • also why do you need intermediary variables? what's wrong with y -> y * 2 + x / 2? Commented Apr 17, 2021 at 22:02
  • the exact example is a toy example. But really I just need to write some code that will we infeasible to write in a single oneliner Commented Apr 17, 2021 at 22:16
  • Have you tried specifying explicit types for the lambda params? Commented Apr 17, 2021 at 22:24
  • Also, the bottom part doesnt work Commented Apr 17, 2021 at 22:24

2 Answers 2

2

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
}}
Sign up to request clarification or add additional context in comments.

Comments

1

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.