Skip to content

Instantly share code, notes, and snippets.

@89465127
Last active December 16, 2015 10:58
Show Gist options
  • Save 89465127/5423833 to your computer and use it in GitHub Desktop.
Save 89465127/5423833 to your computer and use it in GitHub Desktop.
Simple experiments with scala lists and maps.
// define a simple list
scala> val l = List("a", "b", "c")
l: List[java.lang.String] = List(a, b, c)
// print each element of the list
scala> l.foreach{ println }
a
b
c
// same deal, with case syntax
scala> l.foreach{ case(x) => println(x) }
a
b
c
// in fact, you don't actually need the word case
scala> l.foreach{ (x) => println(x) }
a
b
c
// get a counter in the foreach loop
scala> l.zipWithIndex
res10: List[(java.lang.String, Int)] = List((a,0), (b,1), (c,2))
scala> l.zipWithIndex.foreach{ case(letter,i) => println(letter + " : " + i) }
a : 0
b : 1
c : 2
// now lets create a map of letter : index
// note that we use a var, since we want mutability
scala> var fieldToIndex: Map[String, Int] = Map()
fieldToIndex: Map[String,Int] = Map()
// we could add an individual item to the map:
fieldToIndex += ("asdf" -> 1)
//but instead, lets create our map using a loop:
l.zipWithIndex.foreach{ case(field, i) => fieldToIndex += (field -> i) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment