vkubicki
vkubicki

Reputation: 1124

Anonymous function in hash map

I would like to implement a trait that contains a Map string => function, as in:

trait InnerProductSpace[T] {
  def minus(x: T, y: T): T
  def ip(x: T, y: T): Real

  var kernel = Map[String, (T, T) => Real](
    "linear" -> (x: T, y: T) => ip(x, y)
  )
 }

However, I get the compilation error:

Error:(18, 18) not a legal formal parameter.
Note: Tuples cannot be directly destructured in method or function parameters.
      Either create a single parameter accepting the Tuple1,
      or consider a pattern matching anonymous function: `{ case (param1, param1) => ... }
        "linear" -> (x: T, y: T) => ip(x, y)

How can I define the anonymous function properly ?

Upvotes: 1

Views: 51

Answers (1)

AlexITC
AlexITC

Reputation: 1074

The compiler is giving you the hint:

Note: Tuples cannot be directly destructured in method or function parameters.
      Either create a single parameter accepting the Tuple1,
      or consider a pattern matching anonymous function

You compiles fine:

  var kernel = Map[String, (T, T) => Real](
    "linear" -> { case (x, y) => ip(x, y) }
  )

Upvotes: 2

Related Questions