【问题标题】:Invoking Scala class' primary constructor with an implicit parameter inside an auxiliary constructor [duplicate]在辅助构造函数中使用隐式参数调用 Scala 类的主构造函数 [重复]
【发布时间】:2014-06-04 08:09:28
【问题描述】:

编译错误的类定义:

class Foo(implicit x : Int) {
  def this(s : String) = this(s.length)
}

并且类定义可以通过编译

class Foo(implicit x : Int) {
  def this(s : String) = this()(s.length)
}

在我看来,第一个定义是正确的。 由于辅助构造函数显式调用了预期 Integer 作为参数的主构造函数,因此似乎没有错。 而对于通过编译的第二类定义,其实我不太明白为什么会这样。

【问题讨论】:

  • 似乎编译器在您的第一个示例中没有生成主构造函数,并且无法解析对Foo(Int)的调用

标签: scala


【解决方案1】:

在 Scala 中,每个辅助构造函数都必须调用与其第一个操作相同类的另一个构造函数。

此外,您没有带有Int 参数的构造函数。 您有带有 implicit (Int) 参数的构造函数。 您可以在范围内提供隐式参数,也可以将其显式传递给this()(9)

【讨论】:

  • 谢谢,但是 this()(9) 是从哪里来的?或者我需要把它当作一个事实。实际上我搜索了 scala 文档并没有与这种奇怪的语法相关。
猜你喜欢
  • 2019-01-10
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
  • 2014-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多