Home > Net >  Kotlin default parameter and named argument for map
Kotlin default parameter and named argument for map

Time:04-11

I am writing a method and I use default parameter and named argument because sometime, some parameters are not required and it's easier for me to have default value. But I am getting trouble making it work with map.

 fun search(scope: String = "", page: Int = 0, filters: Map<String, String>, withAuthorization: Boolean = false)

Here is my method, it work perfectly fine. I can call it like this :

search("scope", 0, mapOf("filter" to "test"), true)

Or i can omit some of the parameter because they have default value :

search("scope", 0, mapOf("filter" to "test")) 

But default value only work at the end of the method, so I also use named argument with i want to skip on parameter in the middle :

search("scope", filters = mapOf("filter" to "test"), withAuthorization = true) 

All of this work and I'am pretty happy with it, problem is that sometime I have no filter to apply so I would like to not use the filer map as parameter but I did not manage to do it. I tried to add a default parameter like this : filters: Map<String, String> = mapOf() But when i call the method like this : search("scope", 0, withAuthorization = true) I got an error : No value passed for parameter 'filters'

So i would like to know if there is a way to give a map a default parameter or any other way that could prevent me to send my map filter when i don't have to use it because i don't want to send an empty map to my method search.

CodePudding user response:

It should just work how you describe it:

fun search(scope: String = "", page: Int = 0, filters: Map<String, String> = mapOf(), withAuthorization: Boolean = false) {
    ...
}
  • Related