代码之家  ›  专栏  ›  技术社区  ›  Srinivas

scala中伴随对象的问题

  •  1
  • Srinivas  · 技术社区  · 8 年前

    下面的代码编译得很好(这是一个简单的伴生对象教程)

    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
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   prayagupa soxunyi    8 年前

    val r = Colours ,这不是你的电话 apply 因为apply方法没有参数,所以它不接受params ()

    参见示例,

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

    val r = Colours.apply
    

    ( 空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?

        2
  •  1
  •   jwvh    8 年前

    将括号添加到 apply

    def apply(): ...
    

    …和 Colours 对象调用。

    val r = Colours()
    

    然后它将按需要工作。

    r.printColour  // "colour is Red"
    
    推荐文章