list - Covariance and Scala Collections -
i'm trying head around covariance of scala's collections. have following:
abstract class mediaformat{ def name:string def status:string } case class h264_high(status:string="on") extends mediaformat { def name = "h264_high" } case class h264_med(status:string="on") extends mediaformat { def name = "h264_med" } case class h264_low(status:string="on") extends mediaformat { def name = "h264_low" } case class h264_syndication(status:string="off") extends mediaformat { def name = "h264_syndication" } what wanted have set of of these formats because need collection each format occurs once, tried:
object mediaformat { val allformats:set[mediaformat] = set(h264_high,h264_low) } this gave me compile time exception because, understand, set invariant.
so think, guess i'll have use list , manage repeated values myself
but try this:
object mediaformat { val allformats:list[mediaformat] = list(h264_high,h264_low) } because understand it, list is covariant, still doesn't compile.
can me understand should collection of formats?
it doesn't compile because referencing companion object (module), not case classes! compile error (which should have posted) nothing variance. will work, set if this:
val allformats: set[mediaformat] = set(h264_high(), h264_low()) ^^ ^^ or alternatively;
val allformats = set[mediaformat](h264_high(), h264_low()) however, makes no sense these case classes given description of problem; make them modules, i.e.
case object h264_syndication extends mediaformat { def status = "off" def name = "h264_syndication" } then original code work fine. or make them vals follows:
case class mediaformat(status: string, name: string) val h264_syndication = mediaformat(status ="off", name = "h264_syndication") i think preference; use abstract classes more honest (normally, dishonest).
explanation: covariance means following:
g[s] <: g[t]iffs <: t
the fact set invariant, means set[s] not subtype of set[t] (for s <: t), does not mean such set[t] may not contain elements of type s.
Comments
Post a Comment