0

I'm reading the following document : Constructor References

There is explained how to send a referenced to constructor. But they don't described a situation when there is more than one constructor (overloaded constructor). The following code makes an error in compilation because of overload resolution ambiguity:

     open  class Animal (val stttt:String, val str:String = "hjm") {
        constructor(number1: Int, _number2: Int) :this("dsa")
        {
            println("runnnnnn")
        }
     }

function that gets the constructor as parameter:

fun function(factory: () -> Animal) {
    val x: Animal = factory()
}

and here is the problem:

    function(::Animal)

How can i solve this conflict? And how function knows which type of constructor it's gets (depends to the constructor, each constructor needs different arguments)

Eitanos30
  • 1,331
  • 11
  • 19

1 Answers1

1

I think this is just an incorrect error message. The real problem is that none of your constructors match the signature the function requires. Neither of your constructors has zero arguments. In this case you could make your function request a function that has a signature matching one of your constructors:

fun function(factory: (String) -> Animal) {
    val x: Animal = factory("foo")
}

It is possible to create constructor ambiguity through the use of default arguments. This is a problem even without constructor references, so you should avoid doing it in the first place. The compiler should probably have a warning about that.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • If this were a practical factory function, you would need to pass parameters to it that are required by the constructor. Your example class Animal has a contructor that can be called with one String parameter `stttt` (since the second parameter with a default value can be omitted). So in my example I modified the function so you can pass a constructor that takes a single String parameter. – Tenfour04 Nov 09 '20 at 18:28
  • @Tefour04, I think i understand. Thank you! – Eitanos30 Nov 09 '20 at 18:31