首页 > 解决方案 > Scala,如何指定具有多个特征的函数参数?

问题描述

我有以下一段代码,我认为一旦你看到我的问题就会很明显。

trait hasId {
  def id: String
}

trait hasCount {
  def count: Int
}

case class Foo(id: String, count: Int) extends hasId with hasCount

// This is the function I want to write
def printData(data: hasId and hasCount): Unit = {
  println(data.id + ": " data.count);
}

我应该如何声明函数签名?

标签: scala

解决方案


答案的解决方案是with关键字,它用于您的含义and。Terry Dactyl 写的泛型是一种可能的解决方案:

def printData[T <: hasId with hasCount](data: T): Unit = {
  println(data.id + ": " + data.count)
}

另一个是使用type别名with

type hasIdAndCount = hasId with hasCount
def printData(data: hasIdAndCount): Unit = {
  println(data.id + ": " + data.count)
}

甚至直接:

def printData(data: hasId with hasCount): Unit = {
  println(data.id + ": " + data.count)
}

推荐阅读