0

I have a (seemingly) odd problem. It can be reproduced with just a few lines:

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

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

It compiles and works as expected as long as I keep Parent's secondary constructor commented out. Once I put it back in, this lint error pops up where the Child's parent constuctor is called:

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

The error goes away if any of these is true:

  • I specify variance as HashMap<String, out Any>,
  • My secondary constructor is empty,
  • map is declared as Map instead of HashMap (which I don't do because for my purposes I need it to implement Serializable).

To be honest, it doesn't make much sense to me. Why does it happen only if I add non-empty secondary constructor to the parent class? What does it have to do with anything? And how exactly do these "fixes" fix it?

Thanks.

1 Answer 1

2

This may be by design or a compiler bug. I recommend reporting it at Kotlin (KT) | YouTrack.

As a workaround, you can explicitly declare the generic types used in the HashMap when calling the Parent constructor:

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

I'm not certain why the compiler accepts HashMap<String, String> as HashMap<String, Any> when the secondary constructor isn't defined but doesn't accept it when the secondary constructor is defined but sometimes the compiler simply fails to infer generic types and you need to explicitly declare them.

Sign up to request clarification or add additional context in comments.

1 Comment

I assumed I was missing something but yes, it certainly looks like a bug. Thanks, I guess I'll report it then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.