Learning Scala and I keep wanting an equivalent to LINQ's Single() method. Example,
val collection: Seq[SomeType]
val (desiredItem, theOthers) = collection.partition(MyFunc)
desiredItem.single.doSomething
// ^^^^^^
I could use desiredItem.head
but what if MyFunc actually matched several? I want the assurance that there's only one.
Edit #2 The duplicate question says 'no there isn't but here's how to build it'. So I am thinking if this was a common need it would be in the base API. Do properly written Scala programs need this?
Coming to list, head() method is used to get the head/top element of the list.
We can use the head() and last() methods of the class List to get the first and last elements respectively.
Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.
The collect function is applicable to both Scala's Mutable and Immutable collection data structures. The collect method takes a Partial Function as its parameter and applies it to all the elements in the collection to create a new collection which satisfies the Partial Function.
I'd use something more verbose instead of single
:
(desiredItem match {
case Seq(single) => single
case _ => throw IllegalStateException("Not a single element!")
}).doSomething
Its advantage over single
is that it allows you to explicitly control the behavior in exceptional case (trow an exception, return fallback value).
Alternatively you can use destructuring assignment:
val Seq(single) = desiredItem
single.doSomething
In this case you'll get MatchError
if desiredItem
doesn't contain exactly one element.
UPD: I looked again at your code. Destructuring assignment is the way to go for you:
val collection: Seq[SomeType]
val (Seq(desiredItem), theOthers) = collection.partition(MyFunc)
desiredItem.doSomething
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With