This message was deleted.
# getting-started
s
This message was deleted.
e
not unless you redesign the language with Scala-style mixins (and break Java compatibility). delegates can be stateful and interfaces cannot store state
y
An interface usually shouldn't have an opinion on how its methods are implemented. You can always have this as its own implementation, brought in using
by
delegation:
Copy code
interface MyInterface {
  val number: Int
  class Impl: MyInterface { override val number: Int by MyDelegate() }
}
class Foo: MyInterface by MyInterface.Impl()
Or if you really wanna force `MyDelegate`:
Copy code
interface MyInterface {
  /** This property should always return the same value */
  val myDelegate: MyDelegate
}
val MyInterface.number: Int by ReadOnlyProperty<MyInterface, Int> { thisValue, property -> thisValue.myDelegate(thisValue, property) }
e
in the first case, either
Impl
implements all interface methods (and
class MyImplementation : MyInterface by MyInterface.Impl()
could work) or
Impl
is abstract (in which case implementations would use
class MyImplementation : MyInterface.Impl()
and not be allowed other superclasses). depends on your use case but both could have issues.
in the second case I think it would be clearer to
Copy code
interface MyInterface {
  /** This property should always return the same value */
  val myDelegate: MyDelegate

  val number: Int
    get() = myDelegate.getValue(this, MyInterface::number)
}
but I wouldn't like to have it prescribed that way either
y
I didn't wanna overcomplicate it, but you can easily split it into separate interfaces to overcome this problem:
Copy code
interface MyInterface: MyInterface.Fields {
  val someProp: String
  interface Fields { 
    val number: Int
    class Impl: Fields { override val number: Int by MyDelegate() }
  }
}
class Foo: MyInterface, MyInterface.Fields by MyInterface.Fields.Impl() {
  override val someProp = "Hello World"
}
e
yep, as long as
MyDelegate
doesn't need anything else from
this
. (Scala has a cake pattern
trait Impl { this: MyInterface => }
so that such a mixin could make use of other outer methods but it leads to other complexity)
I do agree with your earlier point though; an interface shouldn't declare how its implementations are implemented
default implementations in the interface can be useful if they're default values or simple conversion from another interface member, but I would usually consider it questionable to do much more than that
☝🏻 1