Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: a tricky case involving anonymous subclasses, callbacks, and type parameters

Tags:

scala

I'm not even sure how to describe what I'm doing, except with an example:

class Node

abstract class App {
    def schema: Node
}

def bind(app: App, f: Node => Node) {
    f(app.schema)
}

val app = new App {
    val schema = new Node {
        val child = new Node
    }
}

bind(app, _.child)

This does not compile. I get: error: value child is not a member of this.Node from the bind call.

I'm not sure how to fix this, but I think it probably involves use of parameterized types. I need the type of f's parameter to be that of the actual Node subclass assigned to schema.

EDIT: I can not explicitly name my Node subtypes, as in real life I have entire trees of statically defined Nodes and it would not be practical to name them.

like image 1000
Landon Kuhn Avatar asked Jan 19 '23 02:01

Landon Kuhn


1 Answers

Ǹode has no method child so class App must retain the parameter of the enclosed node:

abstract class App[N <: Node] {
  def schema: N
}

Then you can extend Node to include child:

class ParentNode extends Node {
  def child = new ParentNode
}

Finally you can write bind as:

 def bind[N <: Node](app: App[N], f: N => N) = {
    f(app.schema)
 }

 val app = new App[ParentNode] {
    val schema = new ParentNode
 }
like image 192
paradigmatic Avatar answered Feb 13 '23 16:02

paradigmatic