简体   繁体   中英

How to define trait for adding to Seq?

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?

samples :+= new Sample(...))

If so, I think the problem is that your Sample class doesn't actually extend SampleAPI .

What's happening has to do with the contravariant type parameter of the List type in Scala. If you start with a List[SampleAPI] , then add a Sample to that list, it needs to find the least-upper-bound on the types included in the list to use as the new type parameter. If Sample is a SampleAPI , then the least-upper-bound is just SampleAPI and you get a List[SampleAPI] as the result of the :+= operation. However, if Sample is not a SampleAPI then the least-upper-bound on the two types is just Object , hence your compiler error saying that it was expecting a Seq[SampleAPI] but found a Seq[Object] .

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.

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