简体   繁体   中英

Why can't I access a variable declared in a class, which implements a Java interface, from Scala?

In Java I have a class that implements an interface:

AlertDialog implements DialogInterface

If some variables are declared inside of the interface I could access them:

AlertDialog.BUTTON_POSITIVE

But in Scala the above line does not compile. Seems like it is hidden. Is there any way to access these variables in Scala without creating a new object or doing anything else hacky?

To give slightly more detail: the reason these can't be accesed is that George is talking about static members defined on the interface. Scala doesn't have static members - instead, one creates an object , which is a regular class with a single implementation. When you're extending from a Java interface, Scala will extend only the non-static members, because the static ones are treated as being in a companion object . The companion object is named the same as the interface, so you can access it as DialogInterface.BUTTON_POSITIVE .

There is no way in Scala to have access to these variables from the AlertDialog class but you could use the interface itself as an object to access them.

So you can directly access the variables from the interface:

DialogInterface.BUTTON_POSITIVE

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