Chris Turner
Chris Turner

Reputation: 400

Calling Java method that doesn't take a generic type from Scala

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})

Upvotes: 2

Views: 511

Answers (1)

Brandon McKenzie
Brandon McKenzie

Reputation: 1685

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)

Upvotes: 1

Related Questions