I want to have classes that can mix only specified traits:
class Peter extends Human with Lawful with Evil
class Mag extends Elf with Chaotic with Neutral
Is in Scala a way to do this?
UPD:
trait Law
trait Lawful extends Law
trait LNeutral extends Law
trait Chaotic extends Law
trait Moral
trait Good extends Moral
trait Neutral extends Moral
trait Evil extends Moral
class Hero .........
class Homer extends Hero with Chaotic with Good
I want to define a Hero
class in a way that constrains the client programmer to mix specific traits (Lawful
/LNeutral
/Chaotic
and Good
/Neutral
/Evil
) if he extends the Hero
class. And I want to find some other possibilities to restrict/constrain client code like this.
We can extend from multiple traits, but only one abstract class. Abstract classes can have constructor parameters, whereas traits cannot.
Traits are used to share interfaces and fields between classes. They are similar to Java 8's interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.
Unlike a class, Scala traits cannot be instantiated and have no arguments or parameters. However, you can inherit (extend) them using classes and objects.
Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait.
Perhaps you're looking for restricting self-type declarations. E.g.:
class Human
trait Lawful
trait Lawless
class NiceGuy
extends Human
{
this: Lawful =>
}
class BadGuy
extends Human
{
this: Lawless =>
}
scala> class SuperHero extends NiceGuy
<console>:7: error: illegal inheritance;
self-type SuperHero does not conform to NiceGuy's selftype NiceGuy with Lawful
class SuperHero extends NiceGuy
^
scala> class SuperHero extends NiceGuy with Lawful
defined class SuperHero
scala> class SuperVillain extends BadGuy
<console>:7: error: illegal inheritance;
self-type SuperVillain does not conform to BadGuy's selftype BadGuy with Lawless
class SuperVillain extends BadGuy
^
scala> class SuperVillain extends BadGuy with Lawless
defined class SuperVillain
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With