Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using variable length argument in scala

Tags:

scala

I know how to define a method with variable length argument:

  case class taxonomy(vocabularies:(String,Set[String])*)

and client code is very clean:

  val terms=taxonomy("topics"->Set("economic","politic")
                   ,"tag"->Set("Libya","evolution")
                   )

but I want to Know how can I use this case class when I have a variable (instead of a Sequence of variable) like this:

val notFormattedTerms = Map("topics"->Set("economic","politic")
       ,"tag"->Set("Libya","evolution"))
like image 550
Mohammad Reza Esmaeilzadeh Avatar asked Feb 22 '11 15:02

Mohammad Reza Esmaeilzadeh


People also ask

How do you declare a variable length argument?

Practical Data Science using Python As the name implies, an argument with a variable length can take on a variety of values. You define a variable argument using a '*', for example *args, to show that the function can take a variable number of arguments.

What is the use of variable length arguments?

A variable-length argument is a feature that allows a function to receive any number of arguments. There are situations where a function handles a variable number of arguments according to requirements, such as: Sum of given numbers. Minimum of given numbers and many more.

What are variable length arguments give an example?

Variable-length arguments, abbreviated as varargs, are defined as arguments that can also accept an unlimited amount of data as input. The developer doesn't have to wrap the data in a list or any other sequence while using them. Let's understand the concept with the help of an example.

What is variable argument fields in Scala?

Scala - Function with Variable Arguments This allows clients to pass variable length argument lists to the function. Here, the type of args inside the print Strings function, which is declared as type "String*" is actually Array[String].


1 Answers

taxonomy(notFormattedTerms.toSeq:_*)

With : _* you virtually transform a sequence argument so that it looks as if a several arguments had been passed to the variable length method. This transformation, however, only works for (ordered?) simple sequence types and, as in this case, not for a Map. Therefore, one will have to use an explicit toSeq before.

like image 52
Debilski Avatar answered Sep 23 '22 11:09

Debilski