Tom K Tom K - 1 year ago 149
Scala Question

Scala return types with foreach and map

I'm new to Scala, and I'm getting confused on how functions stitch together and their return types. Consider the following:

val nodes = List(0,1,2)
val links = List(List(1, 2), List(1, 0), List(1,3))

Each node has a bi-directional link, as described in the tuple-pair 'links'. I am attempting to building a map where each node points to it's neighbours, for example

Map(0 -> List(1), 1 -> List(2, 0), 2 -> List(1) )

However, my initial thinking on how to code this has me stumped on why it's returning an empty 'List[Any]' value.

nodes.foreach(z => ( { case List(a,b) => if(a == z) a else if (b == z) b }))

What is the right way to do this?

Answer Source


scala> => (n, links.flatMap {
     | case List(`n`, x) => Some(x)
     | case List(x, `n`) => Some(x)
     | case _ => None }))
res3: List[(Int, List[Int])] = List((0,List(1)), (1,List(2, 0, 3)), (2,List(1)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download