在 scala 函数文字中,我什么时候必须使用 "case" 关键字

In the scala function literal, when do I have to use the "case" keyword

我一直在纠结这个问题,这很烦人 (Scala 2.13.4)。

    case class Coord(x: Int, y: Int)
    val data: List[(Int, Int)] = List( (1,2), (3,4) )

    data.map{ (x,y)  =>
      Coord(x,y)
    }

给我这个错误:

 found   : (Int, Int) => Coord
 required: ((Int, Int)) => Coord

我可以通过添加“case”关键字来解决

    data.map{ case (x,y) =>
      Coord(x,y)
    }

我的问题是什么时候必须使用 'case' 关键字(在此特定情况下和一般情况下)。编译器应该已经知道它会得到一个 Int 元组。似乎大多数时候不需要它。元组是否有特殊规则,因为它们也使用括号?

data.map{ case (x,y) =>
  Coord(x,y)
}

相当于

data.map { tuple =>
  tuple match {
    case (x, y) => Coord(x,y)
  }
}

它叫做 pattern matching anonymous function

在函数字面量中使用 case 从来都不是强制性的。

{ (x, y) => ??? }

定义两个参数的函数,类似于您从代码中得到的

object Foo extends Function2[A, B, C] {
  def apply[A, B, C](x: A, y: B): C = ???
}

传递元组时,元组作为单个参数传递,然后需要在函数内部对其进行解构。以下是解构元组的所有等效方法

{ tuple => 
  val (x, y) = tuple
  ???
}
{ tuple =>
  tuple match {
    case (x, y) => ???
  }
}
{ case (x, y) => ??? }

请注意,如果您有一个接受超过 1 个参数的函数值,该值有一个 tupled 方法将 n 个参数的函数转换为一个函数取 n 个组件的单个元组。

val f = { (x: Int, y: Int) => Coord(x, y) }
// alternatively:
// val f: (Int, Int) => Coord = Coord.apply

val coordinatePairs = List( (1, 2), (3, 4) )
// alternatively:
// val coordinatePairs = List(1 -> 2, 3 -> 4)

coordinatePairs.map(f.tupled)