I have a beginners Scala question. I have a class, Sample which extends the trait SampleAPI. Now I’m trying to build a sequence of Sample instances using seq. I will look something like this:
var samples: Seq[SampleAPI] = Seq()
for(...) {
samples :+= new Sample(...))
}
This gives me the following compiler error: “type mismatch; found : Seq[java.lang.Object] required: Seq[se.uu.medsci.queue.setup.SampleAPI]”
So I tried:
samples :+= (new Sample(sampleName, this, illuminaXMLReportReader)).asInstanceOf[SampleAPI]
Which instead throws a runtime exception, saying that Sample cannot be bast to SampleAPI. I guess that this comes down to a problem in my understanding of the use of traits in Scala. Any help in figuring this out would be much appreciated.
Is the compiler error coming up on this line?
If so, I think the problem is that your
Sampleclass doesn’t actually extendSampleAPI.What’s happening has to do with the contravariant type parameter of the
Listtype in Scala. If you start with aList[SampleAPI], then add aSampleto that list, it needs to find the least-upper-bound on the types included in the list to use as the new type parameter. IfSampleis aSampleAPI, then the least-upper-bound is justSampleAPIand you get aList[SampleAPI]as the result of the:+=operation. However, ifSampleis not aSampleAPIthen the least-upper-bound on the two types is justObject, hence your compiler error saying that it was expecting aSeq[SampleAPI]but found aSeq[Object].