https://kotlinlang.org logo
#announcements
Title
# announcements
d

dasz

08/19/2019, 12:52 PM
Morning, is there a way to detail the inherited property type and still override it from the base class? Example:
Copy code
interface A; class AI: A; interface B (val a: A); class BI (override val a: AI): B
conversion from A -> to AI where AI derives from A
p

Pavlo Liapota

08/19/2019, 12:59 PM
d

dasz

08/19/2019, 1:01 PM
Seems like it is up to Kotlin version
Copy code
error: type of 'x' doesn't match the type of the overridden var-property 'public abstract var x: Line_0.FooBase defined in Line_0.BarBase'
        override var x: FooChild
Kotlin version 1.3.21 (JRE 1.8.0_152-release-1343-b01)
I've changed the 'x' to var
d

diesieben07

08/19/2019, 1:06 PM
If it's a
var
it would violate the Liskov Substitution Principle: The interface specifies that any interface instance can be assigned, but the implementation restricts that to only specific classes.
☝️ 2
👍 1
thats why it's not allowed
Example:
Copy code
interface A {
    var foo: Any
}
class B : A(var foo: String)

val a: A = B("foo")
a.foo = 123 // compiles, because A.foo is any, but it's actually a B, which requires a String...
d

dasz

08/19/2019, 1:16 PM
You are right, however where is the difference between var and val in that case? In both cases it breaks the Liskov Substitution Principle, however with 'val' it compiles as @Pavlo Liapota pointed
d

diesieben07

08/19/2019, 1:18 PM
val
only allows getting values out of the class. If the interface specifies "you can get an
Any
here" then "you can get a `String`" here satisfies that
With
var
however it breaks: "You can put
Any
in here" is not satisfied by "You can put
String
in here"
👍 1
d

dasz

08/19/2019, 1:26 PM
Ok, thank you, I got your point
3 Views