2

I'm trying to assign a lambda expression to the following variable:

val aba : ((Int) -> Double) -> ((Int) -> Double)

the way I am trying to:

aba = {(b: (Int -> (Double))-> {x: Int  -> 5 - 2 * b(x)} }

but i'm getting different errors like:

  1. Expecting comma or ')' (from compiler)
  2. Destructing declaration initializer of type (int) -> Double must have a component1() function (from editor)

I know that if i will omit (Int -> (Double) and leave only b it works:

aba = {b  -> {x: Int  -> 5 - 2 * b(x)} }

But why can't I explicitly write the parameters? Some can tell me what is the problem?

2 Answers 2

5
aba = { (b: (Int -> (Double)) -> { x: Int  -> 5 - 2 * b(x) } }

is incorrect, because you are missing a closing parenthesis (error 1). After fixing that:

aba = { (b: Int -> (Double)) -> { x: Int  -> 5 - 2 * b(x) } }

you run into error 2.

The paratheses around the declaration of b are in this case incorrect syntax.

You tell the compiler that you want to destructure the parameter of the lambda. But the type does not support that because it does not have a component1() function.

aba = { b: Int -> (Double) -> { x: Int  -> 5 - 2 * b(x) } } 

should work.

Note: The reason why you can omit the type declaration of b is that the compiler can infer the type, since it knows the type of aba from the declaration.

Sign up to request clarification or add additional context in comments.

2 Comments

the line of code you wrote isn't working not because of destrcute issue: aba = { b: Int -> (Double) -> { x: Int -> 5 - 2 * b(x) } } The editor says on the line above: "unexpected token (use ';' to separate expression on the same line". And in addition why aba = { b: (Int) -> (Double) -> { x: Int -> 5 - 2 * b(x) } } won't work
@Eitanos30 the line you are quoting is the working one. Regarding the first line in my answer: I copied it from you. No matter what the error message says, the parantheses count is off. It would be a good idea to list the snippets along with their respective error messages next time to avoid confusion.
2

This compiles for me

val aba: ((Int) -> Double) -> ((Int) -> Double) = 
        { b: (Int) -> Double ->
            {x: Int  -> 5 - 2 * b(x)}
        }

you don't need the extra brackets when specifying the type of b

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.