[英]Scala function that requires a type that extends both a class and a trait
我想制作一個函數,其輸入類型為S
,其中S <: ParentClass
和S
也繼承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.