Note that there are some explanatory texts on larger screens.

plurals
  1. PO"Is almost a" relationships in Scala
    primarykey
    data
    text
    <p>I'm trying to design a class hierarchy with a bunch of similar classes that don't quite share a "is a" relationships. Let's call these <code>Model</code> classes. These classes are meant to be paired with a collection similar algorithms which make use the <code>Model</code> classes but do not identically have the same requirements. Let's call these <code>Strategy</code> classes. The trick is that the <code>Strategy</code> classes require many of the same things from the <code>Model</code> classes, but not all <code>Model</code> classes may be able to implement those required methods. I'd like to not have empty "stub" methods that will just throw <code>UnsupportedOperationException</code>s and instead have a type-safe mixin-based way of dealing with this -- is there a design pattern that I can apply?</p> <p>For example,</p> <pre><code>object Main extends App { trait A { def f(one: Int): Int def g(two: Int): Int def h(three: Int): Int } class A1 extends A { override def f(one: Int): Int = {one + 1} override def g(two: Int): Int = {two + 2} override def h(three: Int): Int = {assert(false); 0} } class A2 extends A { override def f(one: Int): Int = {assert(false); 0} override def g(two: Int): Int = {two - 2} override def h(three: Int): Int = {three - 3} } trait B { def combine(i: Int): Int } trait B1 extends B { this: A =&gt; override def combine(i: Int) = {f(i) + g(i)} } trait B2 extends B { this: A =&gt; override def combine(i: Int) = {g(i) + h(i)} } override def main(args: Array[String]): Unit = { val a11 = new A1 with B1 val a22 = new A2 with B2 println(a11.combine(3)) println(a22.combine(3)) val a12 = new A1 with B2 println(a12.combine(3)) } } </code></pre> <p>Here <code>A</code> is a <code>Model</code> class and <code>B</code> is the <code>Strategy</code> class. Notice that <code>A1</code> may not be able to implement <code>h()</code> and that <code>A2</code> may not be able to implement <code>f()</code>, and depending on the strategy class this may or may not be a problem. I'd like to be able to find out which implementation of A can work with which implementation of B at compile time.</p> <p>I've used <a href="http://www.scala-lang.org/node/124" rel="nofollow">self-types</a> to express a more "has a" than "is a" relationship that would normally go with extension.</p>
    singulars
    1. This table or related slice is empty.
    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