Note that there are some explanatory texts on larger screens.

plurals
  1. POReplacement for specialization of method parameters in subclasses
    text
    copied!<p>I would like to create a framework where users are able to subclass a base class, <code>Node</code> which is able to produce a message (here an integer) based on the current instance state, and the properties of another instance (the parameter n). The users should be able to specialize the method <code>getMessage</code> to produce different messages based on the class of the current instance and <em>the class of the parameter n</em>, as shown in the code below.</p> <p>The function <code>importantAlgorithm</code> uses messages generated by these nodes to compute the final results.</p> <pre><code>// Classes defined by the framework // abstract class Node { def getMessage(n: Node) : Int } def importantAlgorithm(lstNodes1: List[_ &lt;: Node], lstNodes2: List[_ &lt;: Node]) = { val results = lstNodes1.zip(lstNodes2).map({case (n1, n2) =&gt; // I would like to get the proper message *BASED ON // THE TYPE OF N1 and N2* val message = n1.getMessage(n2) // Do some work with the message //... //... }) //... } // Classes defined by framework users // class ItemNode(val p: Int) extends Node { override def getMessage(n: UserNode) = { // Compute message based on this ItemNode member variables // and n (instance of UserNode) member variables } override def getMessage(n: ItemNode) = { // Compute message based on this ItemNode member variables // and n (instance of UserNode) member variables // The algorithm is different from the algorithm // used in the previous method } } class UserNode extends Node { override def getMessage(n: OtherNode) = { // Compute message. Same idea as above } } class OtherNode extends Node { override def getMessage(n: UserNode) = { // Compute message. Same idea as above } } // The user should be able to use the framework this way importantAlgorithm(List(new UserNode(), new ItemNode(236), new OtherNode(), List(new OtherNode(), new ItemNode(542), new UserNode())) </code></pre> <p>Of course, Scala does not allow to specialize a parameter of a method in a subclass and the above code does not compile. I could use <code>isInstanceOf[]</code> or RTTI but I have a feeling that I am not thinking properly and not designing my framework properly. <strong>How could I replace the mechanism described in the code sample above by a simpler and cleaner solution ?</strong></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