Search code examples
kotlinpolymorphismdefault-value

Parameters positioning in polymorphic functions in Kotlin


I am new to kotlin and I would like to have two polymorphic functions with a default parameter, but it doesn't seem to work. Here is my code:

private fun add(request: Request, share: Boolean = false, number : Int){
   Do something ... 
}
private fun add(key: String, share: Boolean = false){
   Do something ... 
}

My problem is that I can't use the default value because the compiler doesn't seem to infer it.

add(request,  number)

When I do this, meaning that I want to use the first function with the default value of the boolean, I get an error saying that it requires a string and it found a request.

What I think is that the compiler is confused with default values and polymorphism; it doesn't seem to know witch function to use. Is there any ways to fix this or do I have to explicitly declare the default value each time making the default value useless?


Solution

  • Move the parameter with default value on 3rd place in first function so it would become

    private fun add(request: Request, number : Int, share: Boolean = false){ Do something ...

    it will work. you can solve this by named arguments, for example if you call add(request = request, number = number) It will work as well