Snorlite
Snorlite

Reputation: 327

How to use pattern matching with function values in Scala

I have several functions with same input and output types initialized in an object

object Utils {
  def f1(value: Int): Double = ???
  def f2(value: Int): Double = ???
  def f3(value: Int): Double = ???
}

I have a list of higher order values for those functions:

val x = List(Utils.f1, Utils.f2)

How can I use pattern matching to check which functions of those declared in the object are contained in x? I would like to obtain something similar to the following code:

x(0) match {
  case Utils.f1 => ...
  case Utils.f2 => ...
}

Upvotes: 0

Views: 281

Answers (2)

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

This will be possible if you make f1, f2, f3 vals. Please notice that upon pattern matching the equality by reference will be used

object Utils {
  val f1: Int => Double = _ * 10.0
  val f2: Int => Double = _ * 20.0
  val f3: Int => Double = _ * 30.0
}

val x: Seq[Int => Double] = List(Utils.f1, Utils.f2)

import Utils._

x(0) match {
  case `f1` => println(1)
  case `f2` => println(2)
  case `f3` => println(3)
}

If you keep f1, f2, f3 defs then

object Utils {
  def f1(value: Int): Double = value * 10.0
  def f2(value: Int): Double = value * 20.0
  def f3(value: Int): Double = value * 30.0
}

val x: Seq[Int => Double] = List(Utils.f1, Utils.f2)
  
val f1: Int => Double = Utils.f1
val f2: Int => Double = Utils.f2
val f3: Int => Double = Utils.f3

x(0) match {
  case `f1` => println(1)
  case `f2` => println(2)
  case `f3` => println(3)
}

produces MatchError.

Upvotes: 4

Martijn
Martijn

Reputation: 12102

You can't match against functions, it has no meaningfully defined equality.

Upvotes: 4

Related Questions