Reputation: 13527
I will best explain the scenario with code.
object Helper{
fun getValuesForBlah1(constParam1 : Boolean, constParam2 : String, constParam3 : Float, varParam : Int)
fun getValuesForBlah2(constParam1 : Boolean, constParam2 : String, constParam3 : Float, varParam : SomeClass)
fun getValuesForBlah3(constParam1 : Boolean, constParam2 : String, constParam3 : Float, varParam : SomeOtherClass)
...
....
}
If you look at all the functions, then have all have a set of common parameters and rest variable parameters. Is there a way to tell abstract out the common parameters so that I don't have to repeat them in all the functions?
EDIT
@Google has given a nice answer below. But I am looking for a way in which it can be solved using some language feature. For eg in scala it can be solved using implicit (I am not sure though)?
Upvotes: 1
Views: 126
Reputation: 1555
You can use Kotlin's Any Class. Any is the root of the Kotlin class hierarchy. Every Kotlin class has Any as a superclass.In your case you can implement your methods like:
object Helper {
fun getValuesForBlah(constantParam1: Boolean, constantParam2: String, constantParam3: Float, varParam: Any) {
if (varParam is Int) {
} else if (varParam is SomeClass) {
} else if (varParam is SomeOtherClass) {
}
....
....
}
}
UPDATE: In OOP Approach you can do something like:
object Helper {
data class Param(
val constParam1: Boolean,
val constParam2: String,
val constParam3: Float,
var varParam: Any
)
fun getValuesForBlah(param: Param){
if (param.varParam is Int) {
} else if (param.varParam is SomeClass) {
} else if (param.varParam is SomeOtherClass) {
}
....
....
}
}
Hope it would be helpful for you. :)
Upvotes: 1
Reputation: 10106
Just create class that holds common parameters:
object Helper {
data class Param(
val constParam1: Boolean,
val constParam2: String,
val constParam3: Float
)
fun getValuesForBlah1(param: Param, varParam : Int)
fun getValuesForBlah2(param: Param, varParam : SomeClass)
fun getValuesForBlah3(param: Param, varParam : SomeOtherClass)
}
Upvotes: 2