关于kotlin:向父级添加辅助构造函数会意外影响子类

Adding secondary constructor to parent unexpectedly affects child classes

我有一个(看似)奇怪的问题。只需几行即可复制它:

1
2
3
4
5
open class Parent(val map: HashMap<String, Any>) {
    // constructor(unusedArgument: Int): this(hashMapOf())
}

class Child: Parent(hashMapOf(Pair("key","value")))

只要我不评论Parent的辅助构造函数,它就可以按预期进行编译和工作。
一旦放回原处,就会出现此皮棉错误,其中Child的父构造函数称为:

Error: None of the following functions can be called with the
arguments supplied:

public constructor Parent(map: HashMap) defined in Parent

public constructor Parent(unusedArgument: Int) defined in Parent

如果其中任何一个为真,错误就会消失:

  • 我将方差指定为HashMap<String, out Any>
  • 我的二级构造函数为空,
  • map被声明为map而不是HashMap(我不这样做,因为出于我的目的,我需要它来实现Serializable)。

说实话,这对我来说没有多大意义。为什么只有在将非空的辅助构造函数添加到父类时才发生这种情况?它与什么有什么关系?以及这些"修复程序"究竟如何修复它?

谢谢。


这可能是设计使然或编译器错误。我建议在Kotlin(KT)进行报告| YouTrack。

作为一种解决方法,可以在调用Parent构造函数时显式声明HashMap中使用的泛型类型:

1
class Child : Parent(hashMapOf<String, Any>(Pair("key","value")))

我不确定在未定义辅助构造函数时为什么编译器将HashMap<String, String>作为HashMap<String, Any>接受,但是在定义辅助构造函数时为什么不接受它,但是有时编译器只是无法推断泛型而您需要显式声明它们。