简体   繁体   中英

Translating Java generics to Scala

For unit testing a Scala project, I am writing my own simple javax.sql.DataSource class which basically just wraps a java.sql.DriverManager instance under the covers.

I simply extended javax.sql.DataSource , and for the most part let Eclipse auto-generate stubs for the required methods/functions.

class H2DataSource extends javax.sql.DataSource {

  import java.io.PrintWriter
  import java.sql.DriverManager

  var printWriter : PrintWriter

  Class.forName("org.h2.Driver")

  @throws(classOf[SQLException])
  override def getLogWriter() : PrintWriter = {
    printWriter
  }

  @throws(classOf[SQLException])
  override def getLoginTimeout() : Int = {
    // TODO Auto-generated method stub
    0
  }

  @throws(classOf[SQLException])
  override def setLogWriter(printWriter: PrintWriter) = {
    this.printWriter = printWriter 
  }

  @throws(classOf[SQLException])
  override def setLoginTimeout(seconds: Int) = {
    // TODO Auto-generated method stub
  }

  @throws(classOf[SQLException])
  override def isWrapperFor(iface: Class[_]) : Boolean = {
    // TODO Auto-generated method stub
    false
  }

  @throws(classOf[SQLException])
  override def unwrap[T](iface: java.lang.Class[_]) : T = {
    // TODO Auto-generated method stub
    null.asInstanceOf[T]
  }

  @throws(classOf[SQLException])
  override def getConnection() : Connection = {
    DriverManager.getConnection("jdbc:h2:myH2")
  }

  @throws(classOf[SQLException])
  override def getConnection(user: String, password: String) : Connection = {
    DriverManager.getConnection("jdbc:h2:myH2", user, password)
  }

}

However, I'm running into a compilation problem with the unwrap function... with the compiler telling me that it doesn't override anything.

Here is a side-by-side comparison of unwrap ... the first auto-generated in Java, and the second translated into Scala by myself. Can anyone spot what I'm doing wrong, such that the compiler wouldn't recognize them as equivalent?

@Overrride
public <T> T unwrap(Class<T> iface) throws SQLException {
   return null;
}

...

@throws(classOf[SQLException])
override def unwrap[T](iface: java.lang.Class[_]) : T = {
  null.asInstanceOf[T]
}

Try:

@throws(classOf[SQLException])
override def unwrap[T](iface: Class[T]) : T = {
  null.asInstanceOf[T]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM