Scala函数,需要一个扩展类和特征的类型

时间:2016-07-25 02:47:10

标签: scala function types

我想创建一个输入类型S的函数,其中S <: ParentClassS也继承SomeTrait。我使用S <: ParentClass with SomeTrait创建了一个解决方案并且它编译得很好,但它拒绝满足这些条件的输入。

abstract class Units[T](v: T) { def getVal = v}

trait Dimension
trait Time extends Dimension

trait Quantity[T <: Dimension]
trait Instance[T <: Dimension] {
  def plus[S <: Units[_] with Quantity[T]](q: S)
}

case class Seconds(v: Double) extends Units(v) with Quantity[Time] {
}
case class Timestamp(i: Int) extends Units(i) with Instance[Time] {
  def plus[T <: Units[_] with Quantity[Time]](quantity: T) = Timestamp(2345/*placeholder value*/)
}

当我尝试使用它时:

Timestamp(5).plus(Seconds(4))

我收到错误:

<console>:46: error: inferred type arguments [Seconds] do not conform to method plus's type parameter bounds [T <: Units[_] with Quantity[Time]]
              Timestamp(5).plus(Seconds(4))
                           ^
<console>:46: error: type mismatch;
 found   : Seconds
 required: T
              Timestamp(5).plus(Seconds(4))

红利问题:如何获取具有该类型的项目的值,如代码中所示?

1 个答案:

答案 0 :(得分:1)

您的代码类似于我,包括Scala 2.11.8和Scala 2.10.6。

> console
[info] Starting scala interpreter...
[info] 
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_31).
Type in expressions for evaluation. Or try :help.

scala> abstract class Units[T](v: T) { def getVal = v}
defined class Units

scala> 

scala> trait Dimension
defined trait Dimension

scala> trait Time extends Dimension
defined trait Time

scala> 

scala> trait Quantity[T <: Dimension]
defined trait Quantity

scala> trait Instance[T <: Dimension] {
     |   def plus[S <: Units[_] with Quantity[T]](q: S)
     | }
defined trait Instance

scala> 

scala> case class Seconds(v: Double) extends Units(v) with Quantity[Time] {
     | }
defined class Seconds

scala> case class Timestamp(i: Int) extends Units(i) with Instance[Time] {
     |   def plus[T <: Units[_] with Quantity[Time]](quantity: T) = Timestamp(2345/*placeholder value*/)
     | }
defined class Timestamp

scala> Timestamp(5).plus(Seconds(4))

(2.10.6 REPL控制台基本相同,所以我会跳过它。)