首页 > 解决方案 > 如何在scala函数中使用case关键字?

问题描述

我对case在 scala 的函数体中使用关键字感到困惑。
如何更正以下内容以及case此处的用途是什么?

val fun=(x:Int,y:Int)=>{case(a,b)=>a+b}

标签: scala

解决方案


在您的情况下,case完全没有必要。做就是了

val fun = (x: Int, y: Int) => x + y

case当编译器已经知道它期望什么类型时,可以用来为匿名函数编写某种简写形式。例如,如果您试图构造一个匿名函数以作为参数传递给其他函数(例如 List 的map),或者当您在将函数声明为val.

// explicit type hint for what `fun` is supposed to be
val fun: (Int, Int) => Int = { case (a, b) => a + b }
fun(1, 2) // returns 3

// no explicit type hint, the compiler can't figure out what type a and b are
val f = { case (a, b) => a + b }
        ^
error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ?

// passing a function as an argument where a `(Int, Int) => A` is expected
val listOfTuples = List(1 -> 2, 3 -> 4, 5 -> 6)
listOfTuples.map { case (a, b) => a + b }
// returns List(3, 7, 11)

另一种理解它的方式是,它就像在函数的参数上做一个match块的简写,例如

def addTupleParts(tup: (Int, Int)) = tup match {
  case (a, b) => a + b
}
listOfTuples.map(addTupleParts)
listOfTuples.map { case (a, b) => a + b }

推荐阅读