How to get the first element from a Scala Set

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.”

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.