Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrictions in trait mixing

Tags:

scala

traits

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.

like image 432
Jeriho Avatar asked Apr 28 '10 12:04

Jeriho


People also ask

Can a trait extend multiple traits?

We can extend from multiple traits, but only one abstract class. Abstract classes can have constructor parameters, whereas traits cannot.

When can you use traits?

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.

Can you extend a trait in Scala?

Unlike a class, Scala traits cannot be instantiated and have no arguments or parameters. However, you can inherit (extend) them using classes and objects.

How do traits work in Scala?

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.


1 Answers

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
like image 176
Randall Schulz Avatar answered Oct 07 '22 16:10

Randall Schulz