Scala Upper bounds: value is not a member of type parameter

Why can't the price find the attribute value on SeqValue? It seems so simple that should work.

Im getting an 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 recalculate the price object and pass any type of object that implements SeqValue, because SeqValue matters.

0
generics scala bounds
source share
1 answer

An element of type S in Calc receives shadows due to the parameter of type S the recalc method.

Second mistake: the abstract type S must be defined in the Price class.

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 exactly you are trying to do, but you can highlight the type definition in a separate mixin attribute.

 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) } 
+3
source share

All Articles