scala - 如何在scala函数中使用case关键字?
问题描述
我对case
在 scala 的函数体中使用关键字感到困惑。
如何更正以下内容以及case
此处的用途是什么?
val fun=(x:Int,y:Int)=>{case(a,b)=>a+b}
解决方案
在您的情况下,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 }
推荐阅读
- c# - System.Text.Json使用c#.net core 3.1访问json对象的Json对象
- php - 部署者如何部署最新的发布版本
- php - 我正在尝试在我的 WordPress 网站上禁用虚拟产品的购买按钮
- android - 我可以这样做吗,在滚动视图中滚动视图?
- angular - 如何为导入 fontawesome 图标的项目界面分配正确的类型
- android - 如何在 kotlin 的多个活动中使用相同的 SQLiteOpenHelper 对象
- c# - Unrecognized database format In MS Access due to multiple locks functioning on the database file at the same time
- python - How to get fields values of a model in xml through Python in qweb report odoo 12?
- qt - How to programmatically select multiple rows in QListView?
- java - Add optional header to WebClient get request