I'm currently writing a Kotlin library with an object having multiple methods requirering multiple optional parameters. Since in JAVA you would require to pass null to those parameters I think this is kind of unconfortable. Also overloading is not an solution as I don't know the possible combinations necessarily or there are ways to many possibilities.
class MyObj() {
fun method1(param1: Int, param2: String? = null, param3: Int? = null): String { ... }
fun method2(param1: Int, param2: Float? = null, param3: String? = null): Any { ... }
fun method5(param1: Int, ...): User { ... }
}
In Kotlin I can simply write:
myObj = MyObj()
myObj.method1(param1 = 4711, param3 = 8850)
In Java I need to write:
MyObj myObj = new MyObj()
myObj.method1(4711, null, 8850)
...
myObj.method5("abc", null, null, null, null, 8850, null, null, "def")
Since I have quite a lot of methods with a lot of optionals I thought about just passing a class for each method:
/** For JAVA backwards compatibility */
class Method1(
val param1: Int
) {
param2: String? = null
param3: Int? = null
fun withParam2(value: String) = apply { param2 = value }
fun withParam3(value: Int) = apply { param3 = value }
}
class MyObj() {
fun method1(param1: Int, param2: String? = null, param3: Int? = null): String { ... }
/** For JAVA backwards compatibility */
fun method1(values: Method1) = method1(values.param1, values.param2, values.param3)
}
So in Kotlin I can used named parameters and in Java I could simply write:
MyObj myObj = new MyObj()
myObj.method1(new Method1(4711).withParam3(8850))
From my point of view it looks fairly ugly because I always have to say method1(new Method1()) or method2(new Method2()). Do you think there is a more elegant version of this?
Background: This is for calling a REST API taking lots of optional parameters.