我想知道,由于这个错误,为什么这不起作用
object ws1 {
class MyClass(a: Long)
val biList = List(BigInt(1), BigInt(2))
val mcList = biList map { new MyClass(_.longValue) } // error
//val mcList = biList map { x => new MyClass(x.longValue) } // ok
}
Run Code Online (Sandbox Code Playgroud)
的
missing parameter type for expanded function ((x$1) => x$1.longValue)
Run Code Online (Sandbox Code Playgroud)
或者更确切地说
type mismatch: found ws1.MyClass, required scala.math.BigInt => ?
missing parameter type for expanded function ((x$1) => x$1.longValue)
Run Code Online (Sandbox Code Playgroud)
_快速匿名函数的占位符语法实际上只适用于非常简单的情况.您的错误解释了这里发生了什么:
扩展函数缺少参数类型((x $ 1)=> x $ 1.longValue)
那是怎么回事呢
val mcList = biList map { new MyClass(_.longValue) }
Run Code Online (Sandbox Code Playgroud)
扩大到这个
val mcList = biList map { new MyClass(x => x.longValue) }
Run Code Online (Sandbox Code Playgroud)
lambda是在你放置的地方创建的_,而不是你想要的整个花括号封闭部分.如果你想让它按照你期望的方式工作,你只需要添加3个额外的字符(和一些可选的空格):
val mcList = biList map { x => new MyClass(x.longValue) }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |