我有一个简单的类和一个伴随对象的应用方法重载:
case class A(val s: String,
val x: Int,
val y: Int,
val z: Int,
val foo: Int => Int,
val l: Option[List[String]])
object A {
def apply(s: String, x: Int, y: Int, z: Int, foo: Int => Int) =
new A(s, x, y, z, foo, None)
def apply(s: String, x: Int, y: Int, z: Int, foo: Int => Int, l: List[String]) =
new A(s, x, y, z, foo, Some(l))
}
Run Code Online (Sandbox Code Playgroud)
我们还定义一个函数:
def foo(x: Int): Int = x + 1
Run Code Online (Sandbox Code Playgroud)
使用第一个构造函数工作:
scala> val a1 = A("a1", 1, 2, 3, foo)
a1: A = A(a1,1,2,3,$$Lambda$1842/2112068307@598e02f0,None)
Run Code Online (Sandbox Code Playgroud)
但是使用第二个不会:
val a2 = A("a1", 1, 2, 3, foo, List("b1", "b2"))
<console>:24: error: missing argument list for method foo
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `foo _` or `foo(_)` instead of `foo`.
val a2 = A("a1", 1, 2, 3, foo, List("b1", "b2"))
Run Code Online (Sandbox Code Playgroud)
现在的问题(S):什么是我需要通过的原因foo _
还是foo(_)
,而不只是富作为a1
例子吗?另外,我可以重新定义我的课程,以便可以使用foo
吗?
foo
如果声明为函数,则可以正常工作val
scala> val foo = (x: Int) => x + 1
foo: Int => Int = <function1>
scala> val a1 = A("a1", 1, 2, 3, foo)
a1: A = A(a1,1,2,3,<function1>,None)
scala> val a2 = A("a1", 1, 2, 3, foo, List("b1", "b2"))
a2: A = A(a1,1,2,3,<function1>,Some(List(b1, b2)))
Run Code Online (Sandbox Code Playgroud)
为什么def foo
效果很好,我不确定,但它可能与期望一个函数而不是一个方法a1
有关,因为这显然是 scala 中的两个不同的东西。case class A
归档时间: |
|
查看次数: |
3388 次 |
最近记录: |