【问题标题】:Issue with companion objects in scalascala中伴随对象的问题
【发布时间】:2017-07-13 07:06:56
【问题描述】:

以下代码编译良好(这是一个简单的伴随对象教程)

scala> :paste
// Entering paste mode (ctrl-D to finish)

trait Colours { def printColour: Unit }
object Colours {
private class Red extends Colours { override def printColour = { println ("colour is Red")} }
def apply : Colours = new Red
}

// Exiting paste mode, now interpreting.

defined trait Colours
defined object Colours

当我尝试时

val r = Colours

它工作正常,但是当我使用时

r.printColour 

我收到一个错误

<console>:17: error: value printColour is not a member of object Colours
   r.printColour

【问题讨论】:

    标签: scala


    【解决方案1】:

    当您执行val r = Colours 时,它不会在伴随对象上调用您的apply,因为您的apply 方法不接受参数,因为它没有()

    看例子,

    class MyClass {
      def doSomething : String= "vnjdfkghk"
    }
    
    object MyClass {
      def apply: MyClass = new MyClass()
    }
    
    MyClass.apply.doSomething shouldBe "vnjdfkghk" //explicit apply call
    

    所以,你必须在你的伴生对象上调用 apply

    val r = Colours.apply
    

    否则,apply 必须有括号(empty-paren),这样就不需要显式调用.apply

    例如。

    class MyClass {
      def doSomething : String= "vnjdfkghk"
    }
    
    object MyClass {
      def apply(): MyClass = new MyClass()
    }
    
    MyClass().doSomething shouldBe "vnjdfkghk"
    

    非常有用的资源

    Difference between function with parentheses and without [duplicate]

    Why does Scala need parameterless in addition to zero-parameter methods?

    Why to use empty parentheses in Scala if we can just use no parentheses to define a function which does not need any arguments?

    【讨论】:

    • 我还要补充一点,在 REPL 中你可以看到 r 的类型:Colours.type
    【解决方案2】:

    在您的 apply 方法定义中添加括号 ...

    def apply(): ...
    

    ...和Colours 对象调用。

    val r = Colours()
    

    然后它将按需要工作。

    r.printColour  // "colour is Red"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      相关资源
      最近更新 更多