By Alvin Alexander. Last updated: May 2, 2019
I have no idea what I was thinking, but today I learned (or was reminded) that if you want the first element from a Scala Set
you should use its head
method, or headOption
. For some reason I kept thinking that take
should do the job, but you can see the results in the Scala REPL, where take(1)
returns a Set
:
scala> val s = Set(1,2,3) s: scala.collection.immutable.Set[Int] = Set(1, 2, 3) scala> s.take(1) res0: scala.collection.immutable.Set[Int] = Set(1) scala> s.head res1: Int = 1 scala> s.headOption res2: Option[Int] = Some(1)
Of course it makes sense that take
should return a Set
:
scala> s.take(2) res3: scala.collection.immutable.Set[Int] = Set(1, 2)
but for some reason I couldn’t get that through my head when I was thinking, “Just get the first element.”