https://kotlinlang.org logo
Title
m

MR3Y

04/22/2022, 3:42 PM
Today, I saw something that is new for me in kotlin's syntax. In https://github.com/zach-klippenstein/compose-fractal-nav, there is an interface
FractalParent
that is declared as follows:
internal interface FractalParent : FractalNavScope {
    // ...
    val zoomAnimationSpecFactory: () -> AnimationSpec<Float>
  // ...
}
and the class that implements the interface is:
internal class FractalNavStateImpl : FractalParent {
    // ...
    override lateinit var zoomAnimationSpecFactory: () -> AnimationSpec<Float>
my question is how he was able to override
zoomAnimationSpecFactory
and change its modifier from
val
to
lateinit var
without getting a compilation error?
c

Casey Brooks

04/22/2022, 3:45 PM
Think of it in terms of what a property in an interface actually means. Interfaces cannot actually have backing fields which hold data, so all the compiler knows is that
val zoomAnimationSpecFactory
is effectively no different from
fun getZoomAnimationSpecFactory()
. So when
FractalNavStateImpl
implements the interface,
override lateinit var
does still include that “get function” from the property, which means it is implementing everything required from the interface. It just also adds
fun setZoomAnimationSpecFactory(value)
, effectively
👍 4
e

ephemient

04/22/2022, 3:53 PM
this is explicitly mentioned in the docs, https://kotlinlang.org/docs/inheritance.html#overriding-properties
:thank-you: 1
also
interface Base {
    val foo
}
class Impl {
    override var foo
        private set
}
is a common pattern; this allows
Impl
and nothing else to update the value
m

MR3Y

04/22/2022, 4:19 PM
thanks for the heads-up @ephemient 👏