scala中伴随对象的问题

时间:2017-07-13 07:06:57

标签: scala

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

var data = await GetImageDataAsync(url);
var imageData = NSData.FromArray(data);
imageBitmap = UIImage.LoadFromData(imageData);

当我尝试

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 

2 个答案:

答案 0 :(得分:2)

当你执行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

所以,你必须在你的伴侣对象上调用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?

答案 1 :(得分:1)

apply方法定义...

中添加括号
def apply(): ...

...和Colours对象调用。

val r = Colours()

然后它会按照需要运作。

r.printColour  // "colour is Red"