Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Kotlin, how do I create a list of lambdas where each lambda is of the type (Int) -> List? I'm getting destructuring declaration errors

Tags:

kotlin

I am trying to create a list of lambdas in Kotlin, but am getting the following compile-time error:

 Destructuring declaration initializer of type Int must have a 'component1()' function

Here is my code:

val pathXRanges = listOf<(Int) -> List<Int>>(
                {(extX) -> ((extX - (board.k - 1))..(extX + board.k - 1)).toList()}, // diagonal 1 (y = -x)
                {(extX) -> ((extX - (board.k - 1))..(extX + board.k - 1)).toList()}, // diagonal 2 (y = x)
                {(extX) -> List(board.k * 2 - 2) { extX } }, // x = x
                {(extX) -> ((extX - (board.k - 1))..(extX + board.k - 1)).toList()} // y = y
        )

That's pretty much it! Any help is appreciated, let me know if you need clarification on anything.

Thanks!

like image 927
Henry Westfall Avatar asked Oct 20 '25 18:10

Henry Westfall


1 Answers

Simply remove the brackets from the extX lambda parameter values i.e.:

    val pathXRanges = listOf<(Int) -> List<Int>>(
      { extX -> ((extX - (board.k - 1))..(extX + board.k - 1)).toList() }, // diagonal 1 (y = -x)
      { extX -> ((extX - (board.k - 1))..(extX + board.k - 1)).toList() }, // diagonal 2 (y = x)
      { extX -> List(board.k * 2 - 2) { extX } }, // x = x
      { extX -> ((extX - (board.k - 1))..(extX + board.k - 1)).toList() } // y = y
    )

The brackets indicate to the compiler that the lambda parameter should be destructured, and the parameter's component1() operator function should be called to assign a value to extX.

Of course, Int does not have a component1() function, hence the error:

Destructuring declaration initializer of type Int must have a 'component1()' function`.
like image 147
Raman Avatar answered Oct 25 '25 07:10

Raman