Reputation: 60081
I have a an Interface in Java with the static variable interfaceValue
that I could access as below
public class Experimenting {
public interface MyInteface {
int interfaceValue = 10;
}
class MyImpl implements MyInteface { }
MyImpl myImpl = new MyImpl();
void testing() {
int getInterfaceValue = myImpl.interfaceValue;
}
}
When I convert to Kotlin, it is as below
class Experimenting {
internal var myImpl = MyImpl()
interface MyInteface {
companion object {
val interfaceValue = 10
}
}
internal inner class MyImpl : MyInteface
internal fun testing() {
val getInterfaceValue = myImpl.interfaceValue
}
}
However the myImpl.interfaceValue
is showing compile error sign, where by it doesn't recognize the interfaceValue
. How could I still access my interfaceValue
in Kotlin?
Upvotes: 0
Views: 1111
Reputation: 6783
The conversion converts the static final interfaceValue
to a val
in the companion
Kotlins equivalent of that. Unfortunately the converter is not perfect and sometimes messes thing up. To access it
import com.your.package.Experimenting.MyInteface.Companion.interfaceValue
class Experimenting {
internal var myImpl = MyImpl()
interface MyInteface {
companion object {
const val interfaceValue = 10
}
}
internal inner class MyImpl : MyInteface
internal fun testing() {
val getInterfaceValue = interfaceValue
}
}
does the trick.
also does:
class Experimenting {
internal var myImpl = MyImpl()
interface MyInteface {
companion object {
val interfaceValue = 10
}
}
internal inner class MyImpl : MyInteface
internal fun testing() {
val getInterfaceValue = MyInteface.interfaceValue
}
}
A third way would be to copy the value of interfaceValue
into the implementing class:
class Experimenting {
internal var myImpl = MyImpl()
interface MyInteface {
companion object {
const val interfaceValue = 10
}
}
internal inner class MyImpl : MyInteface{
val interfaceValue = MyInteface.interfaceValue
}
internal fun testing() {
val getInterfaceValue = myImpl.interfaceValue
}
}
Basically you access it like you would access a static variable in java.
Upvotes: 1
Reputation: 60081
I guess the right conversion of such Java code to Kotlin code should be as below
class Experimenting {
internal var myImpl = MyImpl()
interface MyInteface {
val interfaceValue: Int
get() = 10
}
internal inner class MyImpl : MyInteface
internal fun testing() {
val getInterfaceValue = myImpl.interfaceValue
}
}
Though syntactically they are different, i.e. interfaceValue
not really a static variable anymore, but practicality the same.
Upvotes: 0