0

I have a function defined as follows:

getTypeB(id: String, 
         valA1: TypeA = defaultA1
         valA2: TypeA = defaultA2,
         valA3: TypeA = defaultA3 ) : TypeB {}

I know using named arguments I can call the above function with only some of the vals, like

getTypeB(id,
         valA2 = someValueOfTypeA )

My question is, is here any way for the literal text valA2 to be a variable. I wanted to be able call getTypeB from somewhere else, where they won't know the argument argument names unless they're passed in. So is there a way to use a variable for a named argument? If not, us there any other alternative I can use here?

RaminS
  • 2,208
  • 4
  • 22
  • 30
  • Possible duplicate of [Reflectively calling function and using default parameters](https://stackoverflow.com/questions/44792787/reflectively-calling-function-and-using-default-parameters) – Lino Jan 30 '19 at 10:48

1 Answers1

0

You can use map to do this:

fun getTypeB(id: String,
             varsMap: Map<String, TypeA>): TypeB {
    val valA1: TypeA = varsMap.getOrElse("valA1") { defaultA1 }
    val valA2: TypeA = varsMap.getOrElse("valA2") { defaultA2 }
    val valA3: TypeA = varsMap.getOrElse("valA3") { defaultA3 }
    //
}

val args = mapOf(
        "valA1" to someValueOfTypeA,
        "valA2" to someValueOfTypeA)
getTypeB(id, args)
Akaki Kapanadze
  • 2,552
  • 2
  • 11
  • 21