Tom K Tom K - 3 months ago 31
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 => (links.map { case List(a,b) => if(a == z) a else if (b == z) b }))


What is the right way to do this?

Answer

Or,

scala> nodes.map(n => (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)))