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 :
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:如何定义“通用”函数参数?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.