简体   繁体   English

scala中伴随对象的问题

[英]Issue with companion objects in scala

The below code compiles fine (it is a simple companion object tutorial) 下面的代码编译得很好(这是一个简单的伴随对象教程)

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

when i try 当我尝试

val r = Colours

it works fine, but when i use 它工作正常,但当我使用

r.printColour 

I get an error 我收到一个错误

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

When you do val r = Colours , its not calling your apply on companion object because your apply method does not take params because it does not have () . 当你做val r = Colours ,其不打电话给你apply的同伴对象上,因为你的应用方法,因为它没有不采取PARAMS ()

see example, 看例子,

class MyClass {
  def doSomething : String= "vnjdfkghk"
}

object MyClass {
  def apply: MyClass = new MyClass()
}

MyClass.apply.doSomething shouldBe "vnjdfkghk" //explicit apply call

So, you have to call apply on your companion object 因此,您必须在您的伴侣对象上调用apply

val r = Colours.apply

Or else, you must have parenthesis with apply ( empty-paren ), so that you don't need to call .apply explicitly. 否则,您必须使用applyempty-paren )括号,这样您就不需要显式调用.apply

eg. 例如。

class MyClass {
  def doSomething : String= "vnjdfkghk"
}

object MyClass {
  def apply(): MyClass = new MyClass()
}

MyClass().doSomething shouldBe "vnjdfkghk"

very useful resources 非常有用的资源

Difference between function with parentheses and without [duplicate] 带括号的函数与没有[重复]的区别

Why does Scala need parameterless in addition to zero-parameter methods? 除了零参数方法之外,为什么Scala需要无参数?

Why to use empty parentheses in Scala if we can just use no parentheses to define a function which does not need any arguments? 如果我们可以不使用括号来定义不需要任何参数的函数,为什么在Scala中使用空括号?

Add parenthesis to your apply method definition ... 在您的apply方法定义中添加括号...

def apply(): ...

... and the Colours object invocation. ...和Colours对象调用。

val r = Colours()

Then it will work as desired. 然后它将按照需要工作。

r.printColour  // "colour is Red"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM