Java allows default values for interface fields, s...
# language-evolution
h
Java allows default values for interface fields, so why does Kotlin not allow it? or at the very least delegation 😦
d
Kotlin allows default values in interface, but only with using of getters
Copy code
interface A {
    val x: Int
        get() = 1 // OK
    
    val y: Int = 1 // Error
}
If you write
val y = 1
you assume that
y
have backing field, but interfaces can't have state, so you can declare only custom getters/setters
h
but can't java have backing fields in interfaces?
i'm aware that you can use getters, but that doesn't memoize the result. i like to use lazy delegation in abstract classes and the like for relatively expensive field computation
d
when you declare field in java interface that field is static
Copy code
interface Some {
    int x = 1;
}

...
// prints 1
System.out.println(Some.x)
main difference between abstract classes and interfaces in that interface doen't have state, so it's safe to declare multiple interface paretnts (there will be no initialization confllicts dependent of order of initialization)
l
@Hullaballoonatic You're probably looking for
const val
in the
companion object
of the
interface
.
h
What is the intellectual value of interfaces having
no
state vs having a
default
state? (edit: yeah, gotcha. they already support default state via static field values) @louiscad I actually am looking for default instance field values, not static ones, but thanks as that further illustrates the distinction
l
Memory state can only be stored in fields. Interfaces don't support fields. The "interfaces" that do are called abstract classes. A getter with a default implementation can work in an actual interface though, and that value can be cached in the companion object.
h
yeah, abstract classes are a feature i rarely use, given that kotlin's interfaces have so much teeth already. i end up implementing interfaces via delegation more often.
l
Abstract classes have use cases too
h
Yeah I use them occasionally.... When I'm not using sealed classes instead