Let's say I have a Kotlin interface:
interface Dog {
fun walk()
}
I want to create an Kotlin object of this class with slight modifications, like so:
val poodle : Dog = object : Dog {
override fun walk() {
...
}
}
However, I also want to add a what is equivalent to a private static final field in Java to this object, like so (this is a working example in Java):
Dog poodle = new Dog() {
private static final String POODLE_FASHION = ...
@Override
public walk() {
...
}
}
I read that a private const val is equivalent to this in Kotlin. I tried to do the following (this is an example in Kotlin that is NOT working):
val poodle : Dog = object : Dog {
private const val POODLE_FASHION = ...
override fun walk() {
...
}
}
When I did this, I got the following error in Android Studio: Const 'val' are only allowed on top level or in objects.
Could someone explain why the Java version works, but the Kotlin version doesn't? How do I do this for Kotlin (I tried companion object already, but got the error Modifier 'companion' is not applicable inside 'local class')? Note I don't want to do the following because I want POODLE_FASHION
to live inside val poodle
as I am going to create other Dog objects with slight modification as well (val pug
, val chihuahua
, etc.):
private const val POODLE_FASHION = ...
val poodle : Dog = object : Dog {
override fun walk() {
...
}
}
Thanks!