简体   繁体   English

Scala上限:值不是类型参数的成员

[英]Scala Upper Bounds : value is not a member of type parameter

Why can the Price not find the attribute value on the SeqValue? 价格为何无法在SeqValue上找到属性值? It seems so simple that is should work. 看起来很简单,应该可以工作。

Im getting the error 我收到错误

[error]   .... value value is not a member of type parameter SeqValue
[error]   def recalc[SeqValue](input:SeqValue) = Price(1 + seq, input.value)    

for the following code 对于以下代码

sealed trait SeqValue {
  def seq:Int
  def value:Float
  override def toString = ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE)
}

sealed trait Calc {
  type S <: SeqValue
  def recalc[S](input:S):SeqValue
}

case class Price(seq:Int=0, value:Float=.0f) extends SeqValue with Calc {
  def recalc[SeqValue](input:SeqValue) = Price(1 + seq, input.value)
}

The idea is that you can recalc on the price object, and pass in any type of object that implements SeqValue, because SeqValue has a value. 这个想法是您可以重新计算价格对象,并传递实现SeqValue的任何类型的对象,因为SeqValue具有值。

The type member S in Calc is getting shadowed by type parameter S of recalc method. Calc的类型成员Srecalc方法的类型参数S recalc

Second mistake: The abstract type S will have to be defined in class Price . 第二个错误:抽象类型S必须在Price类中定义。

The following should work: 以下应该工作:

sealed trait SeqValue {
  def seq:Int
  def value:Float
  override def toString = ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE)
}

sealed trait Calc {
  type S <: SeqValue
  def recalc(input:S):SeqValue
}

case class Price(seq:Int=0, value:Float=.0f) extends SeqValue with Calc {
  type S = SeqValue
  def recalc(input:SeqValue) = Price(1 + seq, input.value)
}

Edit: (in response to the comment) 编辑:(以回应评论)

I don't understand what you're exactly trying to do, but you could separate out the type definition in a separate mixin trait. 我不明白您到底要做什么,但是您可以在单独的mixin特征中分离出类型定义。

trait SAsSeqValue {
  type S = SeqValue
}

case class Price(seq:Int=0, value:Float=.0f) extends SeqValue with Calc with SAsSeqValue {      
  def recalc(input:SeqValue) = Price(1 + seq, input.value)
}

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

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