简体   繁体   中英

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

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

This will be possible if you make f1 , f2 , f3 val s. 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 def s 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM