Home > Mobile >  Scala How to create an Array of defs/Objects and the call those defs in a foreach?
Scala How to create an Array of defs/Objects and the call those defs in a foreach?

Time:11-04

I have a bunch of Scala objects with def's that do a bunch of processing

Foo\CatProcessing (def processing)
Foo\DogProcessing (def processing)
Foo\BirdProcessing (def processing)

Then I have a my main def that will call all of the individual Foo\obj defProcessing. Passing in common parameter values and such

I am trying to put all the list of objects into an Array or List, and then do a 'Foreach' to loop through the list passing in the parameter values or such. ie

foreach(object in objList){
   object.Processing(parametmers)
}

Coming from C#, I could do this via binders or the like, so who would I manage this is in Scala?

CodePudding user response:

for (obj <- objList) {
  obj.processing(parameters) // `object` is a reserved keyword in Scala
}

or

objList.foreach(obj => obj.processing(parameters))

They are actually the same thing, the former being "syntactic sugar" for the latter.

In the second case, you can bind the only parameter of the anonymous function passed to the foreach function to _, resulting in the following

objList.foreach(_.processing(parameters))

for comprehensions in Scala can be quite expressive and go beyond simple iteration, if you're curious you can read more about it here.

Since you are coming from C#, if by any chance you have had any exposure to LINQ you will find yourself at home with the Scala Collection API. The official documentation is quite extensive in this regard and you can read more about it here.

CodePudding user response:

Using a Map instead, you can do it as such. (wonder if this works through other types of lists)

val test = Map("foobar" -> CatProcessing)

test.values.foreach(
  (movie) => movie.processing(spark)
)
  • Related