Note that there are some explanatory texts on larger screens.

plurals
  1. POScala: Self types in Constructors for generic classes
    text
    copied!<p>Here's a taste of the C# code that I'm porting into Scala. No need to worry about the details.</p> <pre><code>public class GridBase&lt;HexT, SideT, UnitT, SegT&gt; : IGridBase where HexT : Hex where SideT : Side where UnitT : Unit where SegT : ISeg { public GridBase(Geometry&lt;HexT, SideT, UnitT, SegT&gt; geom, IGridBase orig) { this.geom = geom; } } public class Scen: Descrip&lt;HexC, SideC, UnitC&gt;, IListsGeom&lt;HexC, SideC, UnitC&gt; { public Geometry&lt;HexC, SideC, UnitC, ISegC&gt; geomC; public override IGeom iGeom { get { return geomC; } } public HexCList hexCs { get; private set; } public override HexList&lt;HexC&gt; hexs { get { return hexCs; } } public SideCList sideCs { get; private set; } public override SideList&lt;SideC&gt; sides { get { return sideCs; } } public UnitCList unitCs { get; private set; } public override KeyList&lt;UnitC&gt; units { get { return unitCs; } } } </code></pre> <p>As Martin Odersky has pointed out the problem with generics is that the number of type parameters references and their restraint references tend to explode. However for the GridBase class, I need to resolve the types via generics rather than by abstract types. So I want to be able to get multiple types out of one type parameter. So in Scala I create a trait for my types:</p> <pre><code>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 &lt;: Hex type SideT &lt;: 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 } </code></pre> <p>Then I create my Gridbase class using a self type</p> <pre><code>class GridBase[T &lt;: DescripTypes](val myHex: HexT) extends DescripTypes {//Compiler doesn't recognise the HexT type in the constructor other: DescripTypes =&gt; 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 } </code></pre> <p>}</p> <p>For some reason I can't seem to use the type members of DescripTypes in the GridBase Class constructor, although I can use them fine inside the class body. Any help appreciated. But also is this the best way to get multiple types out of one type parameter?</p> <p>Clarification: All Classes are in separate files. No inner classes here.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload