Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala generics with <: and multiple traits

A nearly unknown feature of Java is this generics syntax:

public class Baz<T extends Foo & Bar> {}

I would like to do the same in Scala but I don't know how to do it, can someone give me the syntax please?

I had previously:

class MongoObject[T <: CaseClass]

And now i need:

class MongoObject[T <: IdentifiableModel & CaseClass]

Or at least something similar

Thanks

like image 650
Sebastien Lorber Avatar asked Oct 14 '12 16:10

Sebastien Lorber


People also ask

Can we extend multiple traits in Scala?

A Scala class can extend multiple traits at once, but JVM classes can extend only one parent class. The Scala compiler solves this by creating "copies of each trait to form a tall, single-column hierarchy of the class and traits", a process known as linearization.

Does Scala support multiple inheritance?

Multiple Inheritance Multiple inheritance is the type of inheritance where the subclass inherits directly from more than one class. In Scala, this is not achievable with classes. Instead, multiple inheritance is supported via traits.

Can a trait extend a trait Scala?

Yes they can, a trait that extends a class puts a restriction on what classes can extend that trait - namely, all classes that mix-in that trait must extend that class .

Can you extend multiple classes in Scala?

A Scala trait is just like a Java interface. A trait can be extended by different classes, just the way we do with Java interfaces and also a class can inherit multiple traits, called mixins.


1 Answers

You can use the with keyword just as you would in an extends clause:

class MongoObject[T <: IdentifiableModel with CaseClass]

This means that T has to be a subtype of IdentifiableModel and CaseClass.

like image 77
Kim Stebel Avatar answered Sep 27 '22 20:09

Kim Stebel