This page is no longer maintained — Please continue to the home page at www.scala-lang.org

"Extending" Int

No replies
paulbutcher
Joined: 2010-03-08,
User offline. Last seen 10 weeks 5 days ago.

I want to create a class that "extends" Int (i.e. behaves just like an int, but adds additional functionality). Similar to what RichInt does, in fact.

I've got something that works, but I want to make sure that I'm not missing something, or setting myself up for pain in the future. Here's what I've got:

> class FauxInt(i: Int) { val value = i }
>
> trait LowPriorityImplicits {
> implicit def faux2int(f: FauxInt) = f.value
> }
>
> object FauxInt extends LowPriorityImplicits {
> implicit def faux2rich(f: FauxInt): runtime.RichInt = f.value
> }

Given this, the following works:

> import FauxInt._
>
> val x = new FauxInt(42)
>
> val r1 = 10 + x
> val r2 = x + 10
> val r3 = x < 100
> val r4 = x.min(100)
> val r5 = 100 < x
> val r6 = 100.min(x)

Where are the dragons lurking? And is there a better way?

Thanks!

--
paul.butcher->msgCount++

Snetterton, Castle Combe, Cadwell Park...
Who says I have a one track mind?

http://www.paulbutcher.com/
LinkedIn: http://www.linkedin.com/in/paulbutcher
MSN: paul@paulbutcher.com
AIM: paulrabutcher
Skype: paulrabutcher

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland