https://kotlinlang.org logo
Title
p

Pere Casafont

12/09/2018, 10:51 AM
hi there, what is the best way to solve that problem?:
open class ParentFoo
class ChildFoo : ParentFoo()

abstract class ParentBar {
	open var foo: ParentFoo? = null
}
class ChildBar : ParentBar() {
	override var foo: ChildFoo?
		get() = super.foo as ChildFoo?
		set(value) {
			super.foo = value
		}
}
right now I'm not allowed to set
ChildFoo
as the `ChildBar`'s
foo
property type as it is not exactly the same type as its parent's
foo
, but as it doesn't have a backing field I think this should be able to compile without any problem. What am I missing there?
let's better open a thread, the conversation may become long
@Andreas Sinz @karelpeeters
p

Pavlo Liapota

12/09/2018, 12:17 PM
If it is expected that
ChildBar
should contain only
ChildFoo
in
foo
, then I would have an
abstract val foo
in `ParentBar`:
open class ParentFoo
class ChildFoo : ParentFoo()

abstract class ParentBar {
    abstract val foo: ParentFoo?
}

class ChildBar : ParentBar() {
    override var foo: ChildFoo? = null
}
That way you will be able to get
ParentFoo
from
ParentBar
and get and set
ChildFoo
from
ChildBar
.
You can also use generics:
open class ParentFoo
class ChildFoo : ParentFoo()

abstract class ParentBar<TFoo : ParentFoo> {
    var foo: TFoo? = null
}

class ChildBar : ParentBar<ChildFoo>() {
}
p

Pere Casafont

12/20/2018, 10:21 AM
Thank you, sorry for the late response