简体   繁体   中英

Scala: Implementing Java Interface results in incompatible Type

i have a Java-Interface that i want to implement in Scala. The Interface contains the following method-declaration:

  public Boolean existsTable(String tableId);

My Scala-Implementation is:

  override def existsTable(tableId: String): Boolean = {
    val dbmeta = connection.getMetaData()
    val dbtables = dbmeta.getTables(null, null, channelId, null)
    if (dbtables.next())
      // table exists
      return true
    else
      return false
  }

For some reason i get the error "overriding method existsTable in trait xyz of type (tableId: String)Boolean; method existsTable has incompatible type"

But i dont really know where there could be an incompatible type since its just a Boolean that is the return-type?

Greetings.

PS: I had this method working once before in the exact way, when i wasnt implementing an interface, so there should be no error in the method itself. It's just the Implementation of the Java-Interface in Scala that's giving me a hard time.

The reason why this is not working, as indicated in the comments is that Scala's Boolean is not the same as Java's Boolean. A quick way to fix this is:

import java.lang.{Boolean => JBoolean}

override def existsTable(tableId: String): JBoolean

By aliasing the type, it's a little more clear what you meant to return. You could of course just define it as:

override def existsTable(tableId: String): java.lang.Boolean

The problem is that Scala's Boolean corresponds to Java's boolean , not Java's Boolean . If you change the Java return type to boolean but leave the Scala one as Boolean it should work.

Scala raises all primitive types to the level of real objects, letting the compiler decide to box/unbox them as necessary depending on how they're used. Java, on the other hand, maintains two representations of primitive types: the primitive type itself (small letter) and a boxed representation (capital letter).

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