1

With javaScript I can do something like this:

var parameters = {}
for (object in objects) {
    if (someCondition(object)) {
        parameters.[object.getName()] = object.getValue();
    }
}
myFunction(parameters)

The idea is to collect parameters and pass them as object (!) not as array to the function. How do something similar with scala?

1
  • parameters.[object.getName()] is wrong... no need to use dot after parameters Commented Sep 1, 2014 at 7:48

2 Answers 2

1

This is what Maps are used for. In JavaScript, we use objects interchangeably for "records" and "dictionaries". In Scala, and most statically typed languages, we use Maps instead for the dictionary use case. One advantage of Maps compared to JS dictionaries is that the keys can be of a type different than String.

So I would translate your example as the following, with ObjClass being the class of your objects:

import scala.collection.mutable

val parameters = mutable.Map.empty[String, ObjClass]
for (obj <- objects) {
  parameters(obj.name) = obj.value
}
myFunction(parameters)

Note that the above is very imperative, and can be rewritten in a more functional style like this:

val parameters = (
  for (obj <- objects)
    yield obj.name -> obj.value
).toMap
Sign up to request clarification or add additional context in comments.

3 Comments

The goal is to call myFunction with 1 or 2 or more parameters, not pass Map or tuple object to it. val parameters = (for (obj <- objects) yield obj.name -> obj.value).toMap returns a Map not parameters object.
@Cherry your parameters object acts essentially in the same way as an associative array, which is implemented as Map in Scala. You get the same behaviour but what you lose is static type inference and verification that is one of the major benefits of a statically typed language.
@Cherry I don't get it, then. What is the definition of myFunction?
0

Try with case classes. Define default values as default parameters.

case class Parameters(
  param1:String = "a"
  param2:Int = 1
)

val params = Parameters("b", 2)
myFunction(params)

val paramsWithDefault = Parameters()
myFunction(paramsWithDefault)

You can get something like jquery $.extend behavior with inbuilt features (case classes and default values) of scala. But actually javascript is a dynamic language where you can merge objects, where as scala is static. You define your object in compile time. So what we are doing here is not exactly merging objects.

Furthermore, using parameter objects is not common in scala for clarity of the code.

1 Comment

Not in parameters case class I guess. It really doesn't matter where the myFunction is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.