Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding in Scala, overloaded Java methods distinguished by array type

Tags:

scala

While creating stub implementations of java.sql.Connection, DataSource, ResultSet &c. for a Scala functional test I came across several cases where a Java method is overloaded, with each method distinguished only by the type of an array parameter. For instance (from java.sql.Connection):

PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException
PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException

Converted to Scala, it looks like this:

override def prepareStatement(sql: String, columnIndexes: Array[Int]): PreparedStatement 
override def prepareStatement(sql: String, columnNames: Array[String]): PreparedStatement

but in Scala 2.9.2, this won't compile as we are distinguishing only by a parametric type. Other than implementing the stubs in Java, can anyone propose a clever solution?

I was surprised not to be able to find any prior discussion of this particular Scala/Java interop issue ... it's easy enough to find discussion of the similar issue with varargs. Surely someone has run into this issue before? Any pointers to earlier discussion or issues in the Scala issue tracker?

like image 331
howard branch Avatar asked Sep 30 '14 10:09

howard branch


1 Answers

It's an interesting issue, but it looks like in modern versions of the compiler this has been fixed.

In scala 2.11.2

scala> :paste
// Entering paste mode (ctrl-D to finish)

def prepareStatement(sql: String, columnNames: Array[String]): String = "foo"
def prepareStatement(sql: String, columnIndexes: Array[Int]): String = "bar"

// Exiting paste mode, now interpreting.

prepareStatement: (sql: String, columnNames: Array[String])String <and> (sql: String, columnIndexes: Array[Int])String
prepareStatement: (sql: String, columnNames: Array[String])String <and> (sql: String, columnIndexes: Array[Int])String

scala> prepareStatement("bah", Array(1,2,3))
res11: String = bar

scala> prepareStatement("bah", Array("foo","bar","baz"))
res12: String = foo

and - based on @sjrd's comment - the same works in scala 2.10.0 too.

What version did you test it on?

like image 150
Gabriele Petronella Avatar answered Oct 10 '22 08:10

Gabriele Petronella