简体   繁体   中英

How to return a specific constructor when using reflection?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM