【问题标题】:Scala function that requires a type that extends both a class and a trait需要同时扩展类和特征的类型的 Scala 函数
【发布时间】:2016-11-28 06:41:48
【问题描述】:

我想创建一个函数,它采用输入类型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 function types


    【解决方案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 控制台基本相同,所以我会跳过它。)

    【讨论】:

    • 嗯,我在 Databricks 中进行测试,可能是一些奇怪的工件...我在 REPL 中尝试过,它会进行类型检查,但它也从 plus 函数返回 Unit
    • 好吧,你的plus 函数没有指定它应该返回什么。我猜当你没有指定抽象方法的返回类型时,scala 假设你的意思是 Unit
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 2016-09-13
    相关资源
    最近更新 更多