2

I have a very old Java method that I need to call from Scala. It takes a non-generic version of java.util.Enumeration:

public void someMethod(java.util.Enumeration e) {
    ...
}

I've tried the following code for calling the method:

target.someMethod(new java.util.Enumeration[String] {
  def hasMoreElements = false
  def nextElement = throw new NoSuchElementException()
})

However, this results in a compiler error:

found: java.lang.Object with java.util.Enumeration[String]
required: java.util.Enumeration[?0] where type ?0

I've found plenty of examples for dealing with the case where a Java method returns a non-generic value and you need to handle it with a generic type in Scala. I can't find anything that covers this reverse case where we need to pass a non-generic type instead. Is this possible?

More Information I created an implementation in Java and called it from Scala and it works just fine. The problem only manifests itself when trying to mock the Java method using mockito:

   (java.util.Enumeration[?0],<repeated...>[java.util.Enumeration[?0]])org.mockito.stubbing.OngoingStubbing[java.util.Enumeration[?0]] <and>
   (java.util.Enumeration[?0])org.mockito.stubbing.OngoingStubbing[java.util.Enumeration[?0]]
 cannot be applied to (java.lang.Object with java.util.Enumeration[String]{def nextElement(): Nothing})
3
  • Which version of scala are you working with? I'm using 2.9.2, and your sample code compiles fine. Commented Jul 30, 2012 at 14:25
  • 4
    If you found a solution, you should write it as an answer. Commented Aug 1, 2012 at 15:28
  • 1
    The solution works great. Please, do add it as an answer! Commented May 16, 2016 at 8:36

1 Answer 1

1

Note: Solution was arrived at by asker, but never posted as an answer. What follows is the solution the asker arrived at:

Managed to solve this with some hints from the Odersky book and some hacking with mockito internals. The solution is to build a small function that captures the ?0 type and apply it to the mockito code via a cast:

def thenReturn[T](target: OngoingStubbing[T], result: Any) = 
  target.thenReturn(result.asInstanceOf[T])

thenReturn(when(myMock.someMethod), myEnumeration)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.