10

指定された特性のみを混合できるクラスが必要です。

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

Scalaでこれを行う方法はありますか?

更新:

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

クラスを拡張する場合、クライアント プログラマが特定の特性 ( / /と/ / )Heroを混在させるようにクラスを定義したいと考えています。そして、このようなクライアント コードを制限/制約する他の可能性を見つけたいと思います。LawfulLNeutralChaoticGoodNeutralEvilHero

4

3 に答える 3

28

タフ。これを試して:

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
             ^

Lawタイプを拡張する必要があることを要件にしたい場合は、いくつかの基本クラスまたはトレイトで自己タイプを使用する必要があります。

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[_] =>
}
于 2010-04-28T15:36:27.390 に答える
9

おそらく、自己型宣言の制限を探しているでしょう。例えば:

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
于 2010-04-28T14:06:14.927 に答える
0

Humanand/orのコンストラクターをチェックインしてElf、許可された特性のインスタンスであるかどうかを確認できます。

class Human {
  if (this.instanceOf[Lawful] && this.instanceOf[Chaotic])
    throw new AlignmentException("A Human can only be either Lawful or Chaotic")
}
于 2010-04-28T14:11:00.483 に答える