darkjh
darkjh

Reputation: 2861

scala overrides java class method with inner class and type parameters

I'm working on a java library in scala. There's an abstract class in java:

public abstract class SomeClass<I, O> implements Serializable {
    public abstract class Context {
        public abstract void output(O output) 
    }
    public abstract class ProcessContext extends Context {
        public abstract I element()
    }

    // method to override
    public abstract void process(ProcessContext c) throws Exception
    ...
}

And I've tried to impl a sub-class in scala:

class SubClass extends SomeClass[String, String] {
    override def process(c: SubClass.this.type#ProcessContext) {
        val elem = c.element()

        // problem: elem is not recognized as a string
        if (elem.trim.isEmpty) {...}
        ...
    }
}

So the problem is that the type parameter is kind of 'lost' in the scala sub-class. The elem variable is not recognized as a string.

I've seen the blog by Jeff Hodges at http://www.somethingsimilar.com/2011/01/13/tricky-things-in-scala/ , and tried:

abstract class SSomeClass[I, O] extends DoFn[I, O] {
    type Context = DoFn[I, O]#Context
    type ProcessContext = DoFn[I, O]#ProcessContext
}
class SubClass extends SSomeClass[String, String] {
    ...
    // same problem as before
}

But same problem persists.

Any suggestions?

Thanks!

Upvotes: 2

Views: 121

Answers (1)

som-snytt
som-snytt

Reputation: 39587

This says that the type of element is String. There are probably easier ways to demonstrate it. (currentMirror reflect x).symbol yields the ClassSymbol.

package interop

import reflect.runtime._, universe._

class Subber extends SomeClass[String, String] {
  override def process(c: SomeClass[String, String]#ProcessContext) = {
    val x = c.element
    debug(x)
  }
  def debug[A: TypeTag](a: A) = Console println implicitly[TypeTag[A]]
}
object Test extends App {
  val s = new Subber()
  val c = new s.ProcessContext { def element = "hi" ; def output(x: String) = () }
  s process c
}

Upvotes: 1

Related Questions