diziaq diziaq - 3 months ago 24
Scala Question

Using lambda with generic type in Scala

The second argument of

myFunc
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))
})

x
}


I need to pass second argument to
myFunc
, 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

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))
  x
}

Ad use it like

collect[String, Int](List("1","2","3"), (obj, k, v) => obj.put(k, v.toInt) ) 
Comments