Can someone explain why this code doesn't compile,...
# getting-started
j
Can someone explain why this code doesn't compile, but it does when I change
thing
to a
val
?
Copy code
interface A
interface B {
    var thing: A
}

class Foo : A

class Bar(
	override var thing: Foo
) : B
When
thing
is a
var
, I get this error:
Copy code
Type of 'thing' doesn't match the type of the overridden 'var' property 'var thing: A' defined in '/B'.
p
Return types of overriden functions can be subclasses of overridable function return type. But for input parameters it is not true. Val - is getter with return type of its type. Var - is setter with input parameter of its type.
Copy code
override var thing: Foo
  // fun get() : Foo 
  // fun set(f: Foo)
j
I see. It sort of reminds me of the concept of variance.
☝️ 1
👌 1
l
The reason this isn't allowed is that you could have the following:
Copy code
class Baz: A
val bar = Bar(Foo())
(bar as B).thing = Baz()
And now you've assigned a Baz to a Foo, despite them not being compatible
👍 1