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

Methods In Enumeration Subtypes?

3 replies
Randall R Schulz
Joined: 2008-12-16,
User offline. Last seen 1 year 29 weeks ago.

Hi,

I have this simple Enumeration:

object Polarity
extends Enumeration
{
/** Negative */
val neg = Value

/** Ambipolar */
val amb = Value

/** Positive */
val pos = Value
}

I'd like to define a unary inversion operator (~ or ! or some such) that
I can use like this:

val pol: Polarity = ...
val inv: Polarity = ~pol

The computation is trivial:

def
~(pol: Polarity.Value): Polarity.Value =
pol match {
case neg => pos
case amb => amb
case pos => neg
}

How can I define a method with this behavior that I can use as shown in
the "val inv..." definition above?

Randall Schulz

Naftoli Gugenheim
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Methods In Enumeration Subtypes?
I think  def unary_~ = ...


On Sun, Mar 22, 2009 at 3:26 PM, Randall R Schulz <rschulz@sonic.net> wrote:
Hi,

I have this simple Enumeration:

object          Polarity
extends         Enumeration
{
   /** Negative */
   val neg = Value

   /** Ambipolar */
   val amb = Value

   /** Positive */
   val pos = Value
}


I'd like to define a unary inversion operator (~ or ! or some such) that
I can use like this:

   val pol: Polarity = ...
   val inv: Polarity = ~pol


The computation is trivial:

   def
   ~(pol: Polarity.Value): Polarity.Value =
       pol match {
           case neg => pos
           case amb => amb
           case pos => neg
       }


How can I define a method with this behavior that I can use as shown in
the "val inv..." definition above?


Randall Schulz

Randall R Schulz
Joined: 2008-12-16,
User offline. Last seen 1 year 29 weeks ago.
Re: Methods In Enumeration Subtypes?

On Sunday March 22 2009, Naftoli Gugenheim wrote:
> I think def unary_~ = ...

Oh, sorry.

I was set straight by DRMacIver and others on #scala. The main problem
was that I was trying to define methods in an object derived from
Enumeration. I switched to using case objects instead with the unary
operator method defined in their shared base class.

Randall Schulz

Frank Teubler
Joined: 2009-01-22,
User offline. Last seen 3 years 37 weeks ago.
Re: Methods In Enumeration Subtypes?

You can switch back to Enumeration:

object Polarity extends Enumeration {

class V(s:String) extends Val(s) {
def unary_- = minus(this)
}

val pos = new V("pos")
val amb = new V("amb")
val neg = new V("neg")

private val minus = Map(pos->neg, amb->amb, neg->pos)
}

object Test extends Application {
import Polarity._

println(pos)
println(-pos)
}

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