Ограничения в смешивании черты

Я хочу иметь классы, которые могут смешать только указанные черты:

class Peter extends Human with Lawful with Evil
class Mag extends Elf with Chaotic with Neutral

Находится в Scala способ сделать это?

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

Я хочу определить a Hero класс способом, который вынуждает клиентского программиста смешивать определенные черты (Lawful/LNeutral/Chaotic и Good/Neutral/Evil) если он расширяется Hero класс. И я хочу найти некоторые другие возможности ограничить/ограничить клиентский код как это.

10
задан Erik Kaplun 17 September 2013 в 15:49
поделиться

3 ответа

Жесткий. Попробуйте следующее:

scala> trait Law[T]
defined trait Law

scala> trait Lawful extends Law[Lawful]
defined trait Lawful

scala> trait Chaotic extends Law[Chaotic]
defined trait Chaotic

scala> class Peter extends Lawful with Chaotic
<console>:8: error: illegal inheritance;
 class Peter inherits different type instances of trait Law:
Law[Chaotic] and Law[Lawful]
       class Peter extends Lawful with Chaotic
             ^

Если вы хотите сделать требованием, чтобы тип Закона был расширен, тогда вам нужно использовать собственные типы в каком-то базовом классе или признаке:

scala> class Human {
     |   self: Law[_] =>
     | }
defined class Human

scala> class Peter extends Human
<console>:7: error: illegal inheritance;
 self-type Peter does not conform to Human's selftype Human with Law[_]
       class Peter extends Human
                           ^

И есть еще несколько дополнительных настроек, чтобы гарантировать дальнейшее безопасность типа. Окончательный результат может выглядеть так:

sealed trait Law[T <: Law[T]]
trait Lawful extends Law[Lawful]
trait LNeutral extends Law[LNeutral]
trait Chaotic extends Law[Chaotic]

sealed trait Moral[T <: Moral[T]]
trait Good extends Moral[Good]
trait Neutral extends Moral[Neutral]
trait Evil extends Moral[Evil]

class Human {
  self: Law[_] with Moral[_] =>
}
28
ответ дан 3 December 2019 в 14:06
поделиться

Возможно, вы хотите ограничить объявления собственного типа. Например: [

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
9
ответ дан 3 December 2019 в 14:06
поделиться

Вы можете проверить конструктор Human и/или Elf, если это экземпляр разрешенных признаков:

class Human {
  if (this.instanceOf[Lawful] && this.instanceOf[Chaotic])
    throw new AlignmentException("A Human can only be either Lawful or Chaotic")
}
0
ответ дан 3 December 2019 в 14:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: