下面的代码编译得很好(这是一个简单的伴随对象教程)
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
答案 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?
答案 1 :(得分:1)
在apply
方法定义...
def apply(): ...
...和Colours
对象调用。
val r = Colours()
然后它会按照需要运作。
r.printColour // "colour is Red"