Kotlin`这个`不会在inheritance类中返回正确的实例

我有两个class。 一个是另一个的父母。 我正在实例化Foo中的HashMap的obect,并尝试访问该对象,但在类Bar中,我得到的presenter as Mappresenter as HashMap presenter as Map的引用,因此我的HashMap方法调用都没有工作。

我已经阅读了文档,并试图在init{...}里面指定this.presenter ,就像在Java中一样,但是我仍然无法从子类的内部访问HashMap 。

 open class Foo { var presenter = Map init { presenter = HashMap } } open class Bar : Foo() { //this is trying to call .put on the Map interface, so I get an error presenter.put(someData) } 

您必须将types指定为MutableMap ,还要指定Map的types:

 open class Foo { val presenter: MutableMap = HashMap() } open class Bar : Foo() { //this is trying to call .put on the Map interface, so I get an error fun doit(){ presenter.put("","") } } 

你让编译器推断你的presenter的types,这是一个只读的地图,没有put