Matthew Pocock | 1 Sep 2011 01:44
Picon
Gravatar

Re: Any way to get the effect of Option without always explicitly using Some or None?

Hi,


scalaz has a pimp that adds a .pure function to everything which you could use to wrap your prams into Some. Basically, you're trading Some(42) for 42.pure - depends if you find one or the other form easier to read.

An implicit that goes around promoting anything to Option without some sort of indication from you that you wanted it to is probably a Very Dangerous Thing, and to be avoided. However, you can knock up a pimp like the scalaz one very easily:

case class SomePimp[T](x: T) {
  def some: Some[T] = Some(x)
}

object SomePimp {
  implicit def somePimp{x: T](x: T): SomePimp[T] = SomePimp(x)
}

import SomePimp._

Now, you can say:

42.some
"Sticks and stones".some

Matthew

On 1 September 2011 00:02, Ken McDonald <ykkenmcd-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
I'm doing some work with java.awt.Graphics2D. Rather than explicitly setting and resetting drawing parameters all the time, I'd like to write a function like:

def draw(g2: Graphics2D, drawer: () => Unit, color: Option[Color]=None, x: Option[Int]=None, y: Option[Int]=None,....) and so on for all the parameters I'm interested in. 

The function would take those args that have a Some value, apply them to the Graphics2D, execute "drawer", and then reset the Graphics2D values to their original values.

The only annoyance--and it's one I can live with, but I always like asking questions like this because I learn so much--is that when I call draw, I need to surround all of my drawing parameters with Some. Unpleasant repetition that does nothing to enhance the readability of the code.

I could write implicits to hand this, but those are what I would tend to think of as "dangerous" implicits. In any case, I don't know where I'd put the implicits so that they'd have an effect when I want them to, as I don't have access to the companion objects of either the source or target types.

I could use a builder pattern, but I don't find that as elegant.

So I'm just wondering if there's some wondrously clever solution to this that will enlighten me and make my evening :-)

Thanks,
Ken



--
Dr Matthew Pocock
Visitor, School of Computing Science, Newcastle University
tel: (0191) 2566550
mob: +447535664143


Gmane