2

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?

1
  • 1
    You need to specify that A and B are type parameters, like this: def myFunc[A, B](list: List[A], combine: (Map[A, B], A, A) => Unit) Commented Aug 11, 2016 at 10:30

2 Answers 2

2

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) ) 
Sign up to request clarification or add additional context in comments.

Comments

1

It seems that you are looking to generalise the container being used. Were you looking for something like this? Here we import scala.language.higherKinds so that we can take Container, a kind which takes a single type parameter as a type parameter to addPair.

import scala.language.higherKinds

def addPair[K, V, Container[_]](map: Map[K, Container[V]],
                                addToContainer: (Container[V], V) => Container[V],
                                emptyContainer: => Container[V],
                                pair: (K, V)): Map[K, Container[V]] = {
    val (key, value) = pair
    val existingValues = map.getOrElse(key, emptyContainer)
    val newValues = addToContainer(existingValues, value)

    map + (key -> newValues)
}

Comments

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.