如何使用 Scala 的单例对象类型? [英] How to use Scala's singleton-object types?
问题描述
我正在编写一个类作为一系列单例对象的基类.在每个单例对象中,都会有代表某些属性的 val,我想写一个方法,对于每个单例对象,只接受它创建的对象.
I'm writing a class which serves as base class for a series of singleton objects. In each singleton objects, there will be vals representing certain properties, and I want to write a method which, for each singleton object, only accepts objects created by it.
所以我有以下几点:
class Obj[M <: Maker]
class Maker {
implicit val me: this.type = this
def make[M <: Maker](implicit maker: M) = new Obj[M]
def accept(obj: Obj[this.type]) = {...}
}
到目前为止,一切都很好.然后我想声明这些单例对象之一:
So far, so good. Then I want to declare one of these singleton objects:
object M extends Maker {
val a = make
}
但是,如果我尝试这样做:
But then, if I try this:
M.accept(M.a)
然后我得到一个编译时错误:
then I get a compile-time error:
type mismatch; found : com.test.Obj[object com.test.M] required: com.test.Obj[com.test.M.type]
我的问题:
object com.test.M
的类型是什么,它与com.test.M.type
有什么不同?- 我怎样才能以更智能的方式做到这一点?
- What's the type
object com.test.M
, and how is it different fromcom.test.M.type
? - How can I do this in a smarter way?
推荐答案
与时俱进,我的好人!我在 24 小时前修复了这个问题.接下来,我希望能看到迅猛龙追逐渡渡鸟,一边在点播屏幕保护程序上查看股票报价,一边疯狂地挥舞着他们的马车鞭子.
Get with the times, my good man! I fixed this over 24 hours ago. Next I expect to see velociraptors chasing dodos, furiously cracking their buggy whips while looking up stock quotes on their pointcast screensavers.
有问题的提交是:http://lampsvn.epfl.ch/trac/Scala/changeset/23622
// 1130.scala
class Obj[M <: Maker]
class Maker {
implicit val me: this.type = this
def make[M <: Maker](implicit maker: M) = new Obj[M]
def accept(obj: Obj[this.type]) = ()
}
object M extends Maker {
val a = make
}
object Test {
def main(args: Array[String]): Unit = {
M.accept(M.a)
}
}
// too old
% /scala/inst/scala-2.9.0.r23619/bin/scalac ./1130.scala
./1130.scala:15: error: type mismatch;
found : Obj[object M]
required: Obj[M.type]
M.accept(M.a)
^
one error found
// fresh enough
% /scala/inst/scala-2.9.0.r23624/bin/scalac ./1130.scala
%
这篇关于如何使用 Scala 的单例对象类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!