Thread
#language-evolution
    Hullaballoonatic

    Hullaballoonatic

    2 years ago
    Java allows default values for interface fields, so why does Kotlin not allow it? or at the very least delegation 😦
    dmitriy.novozhilov

    dmitriy.novozhilov

    2 years ago
    Kotlin allows default values in interface, but only with using of getters
    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
    Hullaballoonatic

    Hullaballoonatic

    2 years ago
    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
    dmitriy.novozhilov

    dmitriy.novozhilov

    2 years ago
    when you declare field in java interface that field is static
    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)
    louiscad

    louiscad

    2 years ago
    @Hullaballoonatic You're probably looking for
    const val
    in the
    companion object
    of the
    interface
    .
    Hullaballoonatic

    Hullaballoonatic

    2 years ago
    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
    louiscad

    louiscad

    2 years ago
    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.
    Hullaballoonatic

    Hullaballoonatic

    2 years ago
    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.
    louiscad

    louiscad

    2 years ago
    Abstract classes have use cases too
    Hullaballoonatic

    Hullaballoonatic

    2 years ago
    Yeah I use them occasionally.... When I'm not using sealed classes instead