gildor
06/30/2017, 10:28 AMinit
block
interface MyInterface {
var a: String
}
class ClassA : MyInterface {
override var a = ""
}
kobiburnley
06/30/2017, 10:37 AMgildor
06/30/2017, 10:40 AMinterface MyInterface {
var a: String
}
is compiled to equivalent of Java interface:
interface MyInterface {
String getA();
String setA();
}
So now client must override it.
To behave as property this interface require also field to save value somewhere.
It depends on you how this property should behaveinterface MyInterface {
var a: String
}
class DefaultState : MyInterface {
override var a = ""
}
class ClassA : MyInterface by DefaultState() {
init {
//You have an access to `a` without override
val default = a == ""
}
}
kobiburnley
06/30/2017, 10:50 AMgildor
06/30/2017, 1:32 PMinterface MyInterface {
var a: String
get() = ""
set(value) = TODO()
}
class SomeImpl : MyInterface
var
with val
, because child class can replace var with val itself:
interface MyInterface {
val a: String
get() = ""
}
class SomeImpl : MyInterface
delegation class must override all interface membersActually, from architecture point of view I see no problem with it. You can create partially implemented abstract class and then extend it and implement all other methods and provide resulting class as delegate to an another class (ClassA in you example). Only difference that you have now is separated implementation: 2 classes instead 1 (but it’s not a problem in Kotlin to have them in the same file). But it’s even better, because now you have better code separation and easy replace delegate implementation without changing target class
kobiburnley
07/01/2017, 9:18 AMinterface A {
var mem: String
fun f() {
print("A.f()")
}
}
class DefaultA : A {
override var mem: String = ""
set(value) {
field = value
f()
}
}
class B : A by DefaultA() {
override fun f() {
print("B.f()")
}
}
fun main(args: Array<String>) {
val b = B()
b.mem = "a"
}
Will print "A.f()" although class B overrides it - because the setter of "mem" is called in the scope of "DefaultA"gildor
07/01/2017, 11:31 AMcompiler can enforce a class to overrideWhat do you mean? Compiler force all clients to override all not implemented methods otherwise just throw exception
kobiburnley
07/01/2017, 6:20 PMinterface MyInterface {
var a: String
get() = ""
set(value) = TODO()
}
Try to add custom setter using a backing field - you can't.interface A {
var mem: String = ""
set(value) {
field = value
f()
}
fun f() {
print("A.f()")
}
}
class B : A {
override fun f() {
print("B.f()")
}
}
fun main(args: Array<String>) {
val b = B()
b.mem = "a"
}