Mateusz Dymczyk
Mateusz Dymczyk

Reputation: 15141

AbstractMethodError due to method missing on a trait (library update)

I have a fairly basic scenario, where I'm using a trait from an external library, add an object to a list that's a "global" in that lib:

// my code, list is a Seq in an object from the external library
list.add(new LibraryTrait(){ override def method() = { /* code */ } })

// from an external library, version used at compile time
trait LibraryTrait {
    def method() = {}
}

// from an external library, version used at runtime
trait LibraryTrait {
    def method() = {}
    def method2() = {}
}

At runtime it's failing with an AbstractMethodError, since the anonymous class I'm creating is missing method2() and the library I'm using at runtime is doing a call list.foreach(x -> x.method2()).

Is there anything else I can do, besides compiling against the version that's used at runtime, for it to work?

Not being a scala compiler expert I tried changing my code into this (hoping it will add the method properly):

list.add(new LibraryTrait(){ 
    override def method() = { /* code */ } 
    def method2() = { /* code */ } 
})

But it does not work.

Upvotes: 1

Views: 183

Answers (1)

Mateusz Dymczyk
Mateusz Dymczyk

Reputation: 15141

To answer my own question the fix from my post doesn't work but this seems to compile to a correct form, which works with both versions:

trait MyTrait extends LibraryTrait {
  def method2() {}
}

class MyClass extends MyTrait {
  override def method() = { /* code */ 
}

list.add(new MyClass)

This is a "hack" solution - meaning it works but I'm not sure why so if there's anyone more proficient in the ways of the compiler and could describe the difference in bytecode (anonymous class vs this solution) I'd greatly appreciate it and accept it as the answer.

Upvotes: 2

Related Questions