diziaq diziaq - 1 year ago 149
Scala Question

Using lambda with generic type in Scala

The second argument of

is a function with complex arguments:

def myFunc(list : List[String],
combine: (Map[String, ListBuffer[String]], String, String) => Unit) = {
// body of myFunc is just a stub and doesn't matter
val x = Map[String, ListBuffer[String]]()

list.foreach ((e:String) => {
val spl = e.split(" ")
combine(x, spl(0), spl(1))


I need to pass second argument to
, so it can be used with various types
A, B
insted of specific
String, ListBuffer[String]

def myFunc(list : List[A], combine: (Map[A, B], A, A) => Unit) = {

val x = Map[A, B]() // can this constructor be called with generic types?

list.foreach(e => {
combine(x, e)

How to declare and call such construct?

Answer Source

You can do the following,

def myFunc[A, B](list : List[A], combine: (Map[A, B], A, A) => Unit) = {
  val x = Map[A, B]()
  list.foreach (e => combine(x, e, e))

Ad use it like

collect[String, Int](List("1","2","3"), (obj, k, v) => obj.put(k, v.toInt) ) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download