scala能否在鸭子输入时使用默认参数?
以下代码抛出错误:此处仅允许声明
def test(x: { def x(a:Int, b:Int = 5):Int} ) = x(1)
答案 0 :(得分:0)
不...你不能使用默认参数。此外,您的x(1)应为x.x(1),因为您尝试调用的x是参数上的方法x
,也称为x
。
您可能希望改为执行以下操作:
def test(x: { def foo(a:Int,b:Option[Int]):Int }) = x.foo(1, b.getOrElse(5))
或者使用默认args指定定义方法的特征,并将其混合到要传递给此方法的值中。
答案 1 :(得分:0)
这很俗气:
scala> def test(x: { def x(a:Int, b:Int):Int ; def x$default$2: Int } ) = x.x(1, x.x$default$2)
warning: there were 2 feature warning(s); re-run with -feature for details
test: (x: AnyRef{def x(a: Int,b: Int): Int; def x$default$2: Int})Int
scala> val y = new { def x(a: Int, b: Int = 5): Int = a + b }
y: AnyRef{def x(a: Int,b: Int): Int; def x$default$2: Int @scala.annotation.unchecked.uncheckedVariance} = $anon$1@232864a3
scala> test(y)
res0: Int = 6
宏可以验证默认值是某个常量表达式,大概是。