使用具有不同特征的元素对类型进行类型检查

时间:2012-04-20 20:20:10

标签: scala types typechecking traits

有没有什么方法可以强制一个方法返回一些东西(用正则表达式):

(T with A) (T with A with B)+ (T with B)

如果我返回Traversable[T],它会丢弃绑定的特征。同样,我无法返回Traversable[T with A with B],因为这对于第一个和最后一个元素来说是不准确的。

我不知道如何解决这个问题。它在我的程序中引入了一些隐含条件,我觉得我通过使用.asInstanceOf[]强制转换来滥用类型系统。也许我使用的是错误的数据结构?

以下是我正在撰写的代码示例,以我的意思为例。我希望强制执行route方法。 User类扩展了类型T,我遗漏了代码,因为它有很多。

trait Producer extends User {
  def send(file: Data)
}

trait Consumer extends User {
  def receive(file: Data)
}

...

def route(sender: T with Producer, receiver: T with Consumer): Traversable[T]

def transfer(sender: T with Producer, receiver: T with Consumer, file: Data) {
  val path = route(sender, receiver)
  if (!path.isEmpty) {
    sender send file

    val nextHop = route(sender, receiver).tail.head

    nextHop.asInstanceOf[T with Consumer] receive file

    if (nextHop != receiver) {
      transfer(nextHop.asInstanceOf[T with Producer], receiver, file)
    }
  }
}

1 个答案:

答案 0 :(得分:3)

你绝对应该避免使用.asInstanceOf[]进行投射。

Scala可以轻松地从使用元组的方法返回多个值,那么为什么不返回类型为(T with A, Traversable[T with A with B], T with B)的3元组?

以下是一个例子:

trait A
trait B
class T

def f(): (T with A, Traversable[T with A with B], T with B) = {
  (new T with A, List(new T with A with B), new T with B)
}

val (a, abs, b) = f()