I have a list of integer, need to loop through the list and call different functions which all have the same input parameters, here is my code:
def callRandomFunctions(config: config, prefix: String): ChainBuilder = {
val randomList = Random.shuffle(List(1, 2, 3, 4))
randomList.foreach { _ =>
_ match {
case 1 => func1(config, prefix)
case 2 => func2(config, prefix)
case 3 => func3(config, prefix)
case 4 => func4(config, prefix)
}
}
}
def func1(config: config, prefix: String): ChainBuilder = {...}
def func2(config: config, prefix: String): ChainBuilder = {...}
def func3(config: config, prefix: String): ChainBuilder = {...}
def func4(config: config, prefix: String): ChainBuilder = {...}
and got these errors:
missing parameter type for expanded function
[error] The argument types of an anonymous function must be fully known. (SLS 8.5)
[error] Expected type was: ?
[error] _ match {
[error] ^
[error] type mismatch;
[error] found : Unit
[error] required: io.gatling.core.structure.ChainBuilder
[error] randomList.foreach {
[error] ^
[error] two errors found
Simply shuffle the functions and then call them directly.
def func1(config: config, prefix: String): ChainBuilder = ???
def func2(config: config, prefix: String): ChainBuilder = ???
def func3(config: config, prefix: String): ChainBuilder = ???
def func4(config: config, prefix: String): ChainBuilder = ???
def callRandomFunctions(config: config, prefix: String): Seq[ChainBuilder] =
Random.shuffle(Seq(func1 _, func2 _, func3 _, func4 _))
.map(_(config, prefix))
You can simply do this:
randomList.foreach {
case 1 => func1(config, prefix)
case 2 => func2(config, prefix)
case 3 => func3(config, prefix)
case 4 => func4(config, prefix)
}
and it will work as a pattern matching on number passed to foreach callback.
Another issue with your code is that you want to return ChainBuilder from callRandomFunctions but you're using foreach which is terminating operator returning Unit. You probably wanted to use map and change return type to List[ChainBuilder]:
def callRandomFunctions(config: Config, prefix: String): List[ChainBuilder] = {
val randomList = Random.shuffle(List(1, 2, 3, 4))
randomList.map {
case 1 => func1(config, prefix)
case 2 => func2(config, prefix)
case 3 => func3(config, prefix)
case 4 => func4(config, prefix)
}
}
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