Scala,使用通用特征扩展对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14023712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala, Extend object with a generic trait
提问by Themerius
I'm using Scala and I want to extend a (singleton) object with a trait, which delivers a data structure and some methods, like this:
我正在使用 Scala,我想扩展一个具有特征的(单例)对象,它提供数据结构和一些方法,如下所示:
trait Tray[T] {
val tray = ListBuffer.empty[T]
def add[T] (t: T) = tray += t
def get[T]: List[T] = tray.toList
}
And then I'll would like to mix-in the trait into an object, like this:
然后我想将特征混合到一个对象中,如下所示:
object Test with Tray[Int]
But there are type mismatches in addand get:
但是addand 中存在类型不匹配get:
Test.add(1)
// ...
How can I'll get this to work? Or what is my mistake?
我怎样才能让它发挥作用?或者我的错误是什么?
回答by Travis Brown
The problem is that you're shadowing the trait's type parameter with the Ton the addand getmethods. See my answer herefor more detail about the problem.
问题是你用Tonadd和get方法隐藏了特征的类型参数。有关该问题的更多详细信息,请参阅我的答案here。
Here's the correct code:
这是正确的代码:
trait Tray[T] {
val tray = ListBuffer.empty[T]
def add (t: T) = tray += t // add[T] --> add
def get: List[T] = tray.toList // get[T] --> add
}
object Test extends Tray[Int]
Note the use of extendsin the object definition—see section 5.4 of the specfor an explanation of why withalone doesn't work here.
请注意extends在对象定义中的使用——请参阅规范的第 5.4 节以解释为什么with单独在这里不起作用。

