6
\$\begingroup\$

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?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jul 21, 2015 at 10:06
\$\endgroup\$
0

1 Answer 1

8
\$\begingroup\$

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.

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

  2. 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
 }
}
rolfl
98.1k17 gold badges219 silver badges419 bronze badges
answered Jul 22, 2015 at 14:24
\$\endgroup\$
3
  • \$\begingroup\$ One could also write if (coll.isEmpty || coll.tail.nonEmpty) None else coll.headOption - however I am unsure if it would that be more readable. I am also unsure if perhaps some comment should be there to explain why it works, or perhaps why pattern matching with :: or size are not used instead of head / tail emptyness check. \$\endgroup\$ Commented Jul 22, 2015 at 14:50
  • \$\begingroup\$ Some ScalaDoc would not be a bad idea. \$\endgroup\$ Commented Jul 22, 2015 at 14:59
  • \$\begingroup\$ After thinking about it, I think the way you wrote it originally is probably better. You clearly have three cases (empty, one element, more than one element) and so having three result lines helps to keep that clear. \$\endgroup\$ Commented Jul 22, 2015 at 15:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.