これは、私が Scala に移植している C# コードのテイストです。詳細を気にする必要はありません。
public class GridBase<HexT, SideT, UnitT, SegT> : IGridBase
where HexT : Hex
where SideT : Side
where UnitT : Unit
where SegT : ISeg
{
public GridBase(Geometry<HexT, SideT, UnitT, SegT> geom, IGridBase orig)
{
this.geom = geom;
}
}
public class Scen: Descrip<HexC, SideC, UnitC>, IListsGeom<HexC, SideC, UnitC>
{
public Geometry<HexC, SideC, UnitC, ISegC> geomC;
public override IGeom iGeom { get { return geomC; } }
public HexCList hexCs { get; private set; }
public override HexList<HexC> hexs { get { return hexCs; } }
public SideCList sideCs { get; private set; }
public override SideList<SideC> sides { get { return sideCs; } }
public UnitCList unitCs { get; private set; }
public override KeyList<UnitC> units { get { return unitCs; } }
}
Martin Odersky が指摘したように、ジェネリクスの問題は、型パラメーター参照とその拘束参照の数が急増する傾向があることです。ただし、GridBase クラスの場合、抽象型ではなくジェネリックを介して型を解決する必要があります。そのため、1 つの型パラメーターから複数の型を取得できるようにしたいと考えています。そこで、Scala で型のトレイトを作成します。
abstract class Hex(val num1: Int){} //These are declared in their own files
abstract class Side {val sideString = "This is a side"}
trait DescripTypes //separate file
{
type HexT <: Hex
type SideT <: Side
}
class ScenTypes extends DescripTypes //separate file
{ //This is an ex of an implemntation of the above in a different package
type HexT = HexC
type SideT = SideC
}
次に、自己型を使用して Gridbase クラスを作成します
class GridBase[T <: DescripTypes](val myHex: HexT) extends DescripTypes
{//Compiler doesn't recognise the HexT type in the constructor
other: DescripTypes =>
type other = T
var testvar = 5 //The rest does nothing at useful at the moment
var testvar2 = "" //just for testing
def mymethod(var1: HexT) //Compiler recognises HexT
{
testvar += var1.num1 //This compiles fine
}
def method2(var1: SideT) //Compiler recognises SideT
{
testvar2 = var1.sideString //This compiles fine
}
}
何らかの理由で、GridBase クラス コンストラクターで DescripTypes の型メンバーを使用できないようですが、クラス本体内では問題なく使用できます。どんな助けでも感謝します。しかし、これは 1 つの型パラメーターから複数の型を取得するための最良の方法ですか?
明確化: すべてのクラスは別々のファイルにあります。ここには内部クラスはありません。