【问题标题】:Has scala ability to use default parameter with duck typing?scala 有能力使用鸭子类型的默认参数吗?
【发布时间】:2014-03-21 18:14:15
【问题描述】:

scala 能够使用默认参数和鸭子类型吗?

下面的代码抛出错误:这里只允许声明

def test(x: { def x(a:Int, b:Int = 5):Int} ) = x(1)

【问题讨论】:

  • a) 我很困惑。 b) 这不是鸭子打字,是吗?
  • 是鸭子打字。测试功能需要任何具有适当“x”方法的对象
  • 我不是 Scala 专家,但我认为您需要为此使用特征。我不认为你可以用这种语法做你想做的事情。
  • 好的。我显然错了。每天学习新东西。
  • 我使用一个播放框架,我想将我的观点传递给方法。播放框架从 html 文件编译视图,我不会更改结果对象以使用特征

标签: scala duck-typing


【解决方案1】:

这很俗气:

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

宏可以验证默认值是某个常量表达式,大概是这样。

【讨论】:

    【解决方案2】:

    不...您不能使用默认参数。此外,您的 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))
    

    或者使用默认参数指定定义方法的特征,并将其混合到要传递给该方法的值中。

    【讨论】:

    • 我使用一个播放框架,我想将我的观点传递给方法。播放框架从 html 文件编译视图,我不会更改结果对象以使用特征
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    相关资源
    最近更新 更多