繁体   English   中英

需要一个既扩展类又扩展特性的类型的Scala函数

[英]Scala function that requires a type that extends both a class and a trait

我想制作一个函数,其输入类型为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))

额外的问题:如代码所示,如​​何获取具有该类型的项目的价值?

在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控制台基本上是相同的,因此我将跳过它。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM