简体   繁体   English

使用返回不同数值类型值的方法定义特征

[英]Defining a trait with a method that return a value of different numeric type

I have several classes that contains a numeric value (that value can be bounded, can be only positive, aso...) 我有几个包含数字值的类(该值可以是有界的,只能是正数,也可以...)

I must make some basic operations (like summing) based on a 'supertype' of those classes. 我必须基于这些类的“超类型”进行一些基本操作(如求和)。 So I defined a trait for it thinking it's gonna be trivial... 所以我为它定义了一个特质,认为它会变得微不足道...

Here is a runnable excerpt of my code : 这是我的代码的摘要:

object Main extends App {

  trait WithValue[A] {
    def value: A
  }

  class BoundedNumber[A](val lower: A, val upper: A, val value: A) extends WithValue[A]

  case class NumberBetween0and99(value: Int) extends BoundedNumber[Int](0, 99, value)
  case class UnboundedPositiveInt(value: Int) extends WithValue[Int]
  case class UnboundedPositiveDouble(value: Double) extends WithValue[Double]


  override def main(args: Array[String]) {
    val map: Map[Symbol, WithValue[_]] = Map(
      'foo -> UnboundedPositiveDouble(5),
      'bar -> UnboundedPositiveInt(10),
      'baz -> NumberBetween0and99(55)
    )
    for (m <- map) println(5 + m._2.value)
  }
}

The for loop fail : for循环失败:

overloaded method value + with alternatives: (...) cannot be applied to (Any)

I am running in circle with this really trivial problem for some hours... guess my fluency in Scala is far from 'fluent'... 我在这个小问题上跑了好几个小时。。。猜猜我在Scala的流利程度远非“流利” ...

我认为您可以使用类似的方法来解决您的问题: Scala:如何定义“通用”函数参数?

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

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