How to assign a lambda expression to function type variable?

Viewed 216

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

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

Related