Note that there are some explanatory texts on larger screens.

plurals
  1. POType-parametrized class with default type parameter
    primarykey
    data
    text
    <p>For example, I have the following class hierarchy:</p> <pre><code>abstract class A { def a() {} def aa() } class B extends A { def aa() {} def b() } class C extends A { def aa() {} def c() } </code></pre> <p>And then I want to create a class that can store a collection of any combination of these classes instances. It will be able to call common methods. And due to type parametrization it must provide the ability to call class-specific methods if parametrized with these classes during the creation:</p> <pre><code>object Group { def apply(as: Buffer[A]) = new Group[A](as) def apply[T &lt;: A](as: Buffer[T]) = new Group[T](as) } class Group[T &lt;: A](as: Buffer[T]) { def a() { as.map(_.a()) } def aa() { as.map(_.aa()) } } </code></pre> <p>so the <code>Group</code> can be created with the default, most generic type parameter like this:</p> <pre><code>val groupA = Group(Buffer[A]()) groupA.a() //ok groupA.aa() //ok groupA.b() //error groupA.c() //error </code></pre> <p>and it can be created when parametrized explicitly with one of the descendants of <code>A</code>:</p> <pre><code>val groupB = Group[B](Buffer[B]()) groupB.a() //ok groupB.aa() //ok groupB.b() //ok groupB.c() //error </code></pre> <p>and if it is possible, I would like to somehow remove the unnecessary type specification of <code>[B]</code> when creating the group, since it can be extracted from the passed buffer type:</p> <pre><code>val groupB = Group(Buffer[B]()) </code></pre> <p>What is the correct way of realization of this functionality? Is it possible? Maybe there is a better architectural decision to accomplish this?</p> <p><strong>UPDATE:</strong> the code here is pseudocode, I just don't know how to write what I want.</p> <p><strong>UPDATE 2:</strong> I guess that calling type-specific methods like <code>b()</code> or <code>c()</code> should be realized through mapping:</p> <pre><code>groupC.as.map(_.c()) </code></pre> <p>which is <em>only</em> possible, if the type parametrization is correct. That gets closer to my idea, but the exact possible way of realization remains a mystery (aside from a bunch of usages of <code>asInstanceOf</code> things)..</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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