HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Return the element of collection if the collection contains only one element

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thereturncollectiononecontainselementonly

Problem

Recently I have found in my code several places where I was first gathering some solutions, and then continued processing them only if the solution was unique (solution collection contained only one element). Following code is an attempt to solve this in a more functional manner.

implicit class GetOnlyOne[A](val coll: Iterable[A]) {
    def getonlyone = {
      if (coll.isEmpty) None
      else if (coll.tail.isEmpty) coll.headOption
      else None
    }
  }


The function can be used like:

Seq(1).getonlyone
Seq(1,2).getonlyone
Set(1).getonlyone


Is there anything missing to be idiomatic Scala, or to be more elegant?

Solution

I think that, considering the constraints of your situation (Iterable), the implementation is about as good as it's going to get.

However, that does not mean there aren't things that couldn't be improved.

-
Camel case is standard for method names. I find getOnlyOne to be easier to read than the all lower case version.

-
It has become more of a standard to declare the result type of methods, especially if the method is part of an API. Unless it's a one-line method whose return type is blindingly obvious.

implicit class GetOnlyOne[A](val coll: Iterable[A]) {
  def getOnlyOne: Option[A] = {
    if (coll.isEmpty) None
    else if (coll.tail.isEmpty) coll.headOption
    else None
  }
}

Code Snippets

implicit class GetOnlyOne[A](val coll: Iterable[A]) {
  def getOnlyOne: Option[A] = {
    if (coll.isEmpty) None
    else if (coll.tail.isEmpty) coll.headOption
    else None
  }
}

Context

StackExchange Code Review Q#97563, answer score: 8

Revisions (0)

No revisions yet.