Function - Using lambda with generic type in Scala

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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 instead of specific String, ListBuffer[String].

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

    val x = Map[A, B]()

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

How to declare and call such construct?

Answers

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

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

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/38893676/using-lambda-with-generic-type-in-scala

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils