Scala - “if(true) Some(1)” without having to type “else None”

In scala, if you have an Option, you can get another Option by doing What I want to do is take a boolean and do the same thing. In other words, I want shorthand for the following:


Is there an idiomatic way to get an Option out of a Boolean like this without having to do "else None"?


Scalaz has this. The code would look like this:

import scalaz._
import Scalaz._
val b = true  
val opt = b option "foo"

The type of opt will be Option[String]

If you don't mind creating the data every time,


will do the trick. If you do mind creating the data every time,

Option(someCondition).filter(_ == true).map(_ => data)

but I don't think that's any clearer. I'd go with if-else if I were you.

Or you could

def onlyIf[A](p: Boolean)(a: => A) = if (p) Some(a) else None

and then

onlyIf(someCondition){ data }

Need Your Help

Java: Would using setClip in Graphics be more efficient?

java image clip

I have an off screen BufferedImage that too large to be displayed all at once. So I'm using getSubimage to draw part of the entire image. I'm wondering if using setClip on the Graphics would use less

python 3.2 - find second smallest number in a list using recursion

python recursion python-3.2

So I need to find the second smallest number within a list of integers using recursion but I cannot for the life of me devise a way to do it. I can do it with to find smallest number using this:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.