In my project I have a function like this:
fun doCoolStuff(arg1: Int = 0, arg2: String? = null) {
}
Which I want it to use it in following cases:
obj.doCoolStuff(101) // only first argument provided
obj.doCoolStuff("102") // only second argument provided
obj.doCoolStuff(103, "104") // both arguments provided
But not in this one:
obj.doCoolStuff() // illegal case, should not be able to call the function like this
How do I achieve this on the syntax level?
There is no syntax in Kotlin that would allow you to accomplish what you need. Use overloaded functions (I'd use two, one for each required argument):
fun doCoolStuff(arg1: Int, arg2: String? = null) { ... }
fun doCoolStuff(arg2: String?) { doCoolStuff(defaultIntValue(), arg2) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With