Reputation: 2071
Is there any elegant way to return None rather than an object if the string inputted is empty?
bellow is a crude example of what I want to achieve
private def foo(input: String): Option[Object] = {
Some(Object(input)) //return None instead if input is empty
}
*PS : What I mean by elegant is for me to not create/define another function to achieve this
Upvotes: 1
Views: 264
Reputation: 381
For completeness, following @jwvh answer, Option.unless
uses the negated predicate as declared in Option.when
,
private def foo(input: String): Option[Object] = {
Option.unless(input.isEmpty)(Object(input))
}
Upvotes: 1
Reputation: 8036
def foo(input: String): Option[Object] =
if(input.nonEmpty)
Some(Object(input))
else
None
It will be instantly parsed by anyone reading your code, so really, it doesn't get better than that.
Upvotes: 1
Reputation: 51271
Scala 2.13.x offers the Option.when()
method.
def foo(input: String): Option[Object] =
Option.when(input.nonEmpty)(Object(input))
Upvotes: 5