https://kotlinlang.org logo
h

Hullaballoonatic

12/01/2019, 3:56 AM
Java allows default values for interface fields, so why does Kotlin not allow it? or at the very least delegation 😦
d

dmitriy.novozhilov

12/01/2019, 6:31 AM
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

Hullaballoonatic

12/01/2019, 6:59 AM
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

dmitriy.novozhilov

12/01/2019, 7:10 AM
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

louiscad

12/01/2019, 9:02 AM
@Hullaballoonatic You're probably looking for
const val
in the
companion object
of the
interface
.
h

Hullaballoonatic

12/01/2019, 7:21 PM
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

louiscad

12/01/2019, 7:30 PM
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

Hullaballoonatic

12/01/2019, 7:37 PM
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

louiscad

12/01/2019, 7:40 PM
Abstract classes have use cases too
h

Hullaballoonatic

12/01/2019, 7:41 PM
Yeah I use them occasionally.... When I'm not using sealed classes instead
6 Views