Scala,使用通用特征扩展对象 [英] Scala, Extend object with a generic trait

查看:98
本文介绍了Scala,使用通用特征扩展对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Scala,我想扩展一个具有特征的(单例)对象,该特征可以提供数据结构和一些方法,例如:

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:

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]

但是addget中存在类型不匹配:

But there are type mismatches in add and get:

Test.add(1)
// ...

我如何才能使它正常工作?还是我的错误是什么?

How can I'll get this to work? Or what is my mistake?

推荐答案

问题是您正在使用addget方法上的T遮盖特征的type参数.请参阅我的答案此处以获取有关该问题的更多详细信息.

The problem is that you're shadowing the trait's type parameter with the T on the add and get methods. See my answer here for more detail about the problem.

这是正确的代码:

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]

请注意在对象定义中使用extends-请参阅规范,解释为什么单独的with在这里不起作用.

Note the use of extends in the object definition—see section 5.4 of the spec for an explanation of why with alone doesn't work here.

这篇关于Scala,使用通用特征扩展对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆