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

java enums more compact, flexible and obvious than scala's equivalent?

93 replies
Ken McDonald
Joined: 2011-02-13,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's
Given that solutions like this seem to be popular (using sealed traits/objects and objects/case object/case classes), perhaps an idea might be to to have some discussion on the "most liked" such method, and then put in some syntactic sugar in Scala for supporting "enums" using this method? This eliminates the objection of adding special purpose enums to Scala, and would seem to provide the functionality that is missing from Scala's current "Enum".
Just a thought,Ken
Joshua.Suereth
Joined: 2008-09-02,
User offline. Last seen 32 weeks 5 days ago.
Re: java enums more compact, flexible and obvious than scala's
http://memegenerator.net/instance/7936963

On Tue, Jun 28, 2011 at 1:29 PM, Ken McDonald <ykkenmcd [at] gmail [dot] com> wrote:
Given that solutions like this seem to be popular (using sealed traits/objects and objects/case object/case classes), perhaps an idea might be to to have some discussion on the "most liked" such method, and then put in some syntactic sugar in Scala for supporting "enums" using this method? This eliminates the objection of adding special purpose enums to Scala, and would seem to provide the functionality that is missing from Scala's current "Enum".
Just a thought,Ken

Joshua.Suereth
Joined: 2008-09-02,
User offline. Last seen 32 weeks 5 days ago.
Re: java enums more compact, flexible and obvious than scala's
Even better...


On Tue, Jun 28, 2011 at 12:54 PM, Ken McDonald <ykkenmcd [at] gmail [dot] com> wrote:
> On 06/27/2011 08:25 AM, Matthew Pocock wrote:
> > I don't personally find responses along the lines of, "learn
> > category theory" and, "you should understand algebra" either leads
> > anyone towards enlightenment or welcomes them into the scala
> > community.

These things are _fundamental_ to this profession. If you won't learn
them, you don't deserve the attribute "professional."


Um, no, they are not. There are a great many true professionals out there writing fantastic, tight, reliable code, who don't have a clue what category theory or algebraic data types are. I worked for a company (Be Inc.) that was filled with them, and I read their code. Unit testing is _fundamental_ to this profession. Consistent APIs are _fundamental_ to this profession. Category theory--_not_ fundamental. Nice to have, and if someone points me to good tutorials on cat theory and alg data types I'll go through them--but hey, I'm unemployed.
There is a very funny/sad book called "Night Watch" by Terry Pratchett that talks about how, if political revolution isn't accepted by the people, then the obvious next step is that you need to change the people. I sense some amount of that feeling around Scala--"if people don't see the brilliance of Scala, then the people need to be changed." Well, people do see a lot of the brilliance of Scala, and that's great; but enums are something the keep coming up, which should make us think not, "how do we change people", but, "how do we do enums properly in Scala in a way that will be accepted by the audience we are aiming at.
Oh and I'm serious about the tutorials, so please feel free to provide links.
Ken

Kevin Wright 2
Joined: 2010-05-30,
User offline. Last seen 26 weeks 4 days ago.
Re: java enums more compact, flexible and obvious than scala's
But... but... this is scala-user!


On 28 June 2011 18:46, Josh Suereth <joshua [dot] suereth [at] gmail [dot] com> wrote:
Even better...


On Tue, Jun 28, 2011 at 12:54 PM, Ken McDonald <ykkenmcd [at] gmail [dot] com> wrote:
> On 06/27/2011 08:25 AM, Matthew Pocock wrote:
> > I don't personally find responses along the lines of, "learn
> > category theory" and, "you should understand algebra" either leads
> > anyone towards enlightenment or welcomes them into the scala
> > community.

These things are _fundamental_ to this profession. If you won't learn
them, you don't deserve the attribute "professional."


Um, no, they are not. There are a great many true professionals out there writing fantastic, tight, reliable code, who don't have a clue what category theory or algebraic data types are. I worked for a company (Be Inc.) that was filled with them, and I read their code. Unit testing is _fundamental_ to this profession. Consistent APIs are _fundamental_ to this profession. Category theory--_not_ fundamental. Nice to have, and if someone points me to good tutorials on cat theory and alg data types I'll go through them--but hey, I'm unemployed.
There is a very funny/sad book called "Night Watch" by Terry Pratchett that talks about how, if political revolution isn't accepted by the people, then the obvious next step is that you need to change the people. I sense some amount of that feeling around Scala--"if people don't see the brilliance of Scala, then the people need to be changed." Well, people do see a lot of the brilliance of Scala, and that's great; but enums are something the keep coming up, which should make us think not, "how do we change people", but, "how do we do enums properly in Scala in a way that will be accepted by the audience we are aiming at.
Oh and I'm serious about the tutorials, so please feel free to provide links.
Ken



Russ P.
Joined: 2009-01-31,
User offline. Last seen 1 year 26 weeks ago.
Re: java enums more compact, flexible and obvious than scala's
On Tue, Jun 28, 2011 at 10:29 AM, Ken McDonald <ykkenmcd [at] gmail [dot] com> wrote:
Given that solutions like this seem to be popular (using sealed traits/objects and objects/case object/case classes), perhaps an idea might be to to have some discussion on the "most liked" such method, and then put in some syntactic sugar in Scala for supporting "enums" using this method? This eliminates the objection of adding special purpose enums to Scala, and would seem to provide the functionality that is missing from Scala's current "Enum".
Just a thought,Ken


I tend to agree. Short of that, I suggest that a brief tutorial be added to the official Scala website explaining how best to implement enums. If one is already there, please tell me where to find it. When I google "scala enums," all I see is some random discussion. Sure, some of it is helpful, and I was able to get the information I needed, but it seems to me that there should be something more polished out there than some rambling, unedited online discussion, frozen in time, complete with typos. Is that reasonable?

--Russ P.

--
http://RussP.us
dcsobral
Joined: 2009-04-23,
User offline. Last seen 38 weeks 5 days ago.
Re: java enums more compact, flexible and obvious than scala's
1. Where are the unicorns?
2. Where are the kittens?
3. Can I have a poney?

On Tue, Jun 28, 2011 at 14:46, Josh Suereth <joshua [dot] suereth [at] gmail [dot] com> wrote:
Even better...


On Tue, Jun 28, 2011 at 12:54 PM, Ken McDonald <ykkenmcd [at] gmail [dot] com> wrote:
> On 06/27/2011 08:25 AM, Matthew Pocock wrote:
> > I don't personally find responses along the lines of, "learn
> > category theory" and, "you should understand algebra" either leads
> > anyone towards enlightenment or welcomes them into the scala
> > community.

These things are _fundamental_ to this profession. If you won't learn
them, you don't deserve the attribute "professional."


Um, no, they are not. There are a great many true professionals out there writing fantastic, tight, reliable code, who don't have a clue what category theory or algebraic data types are. I worked for a company (Be Inc.) that was filled with them, and I read their code. Unit testing is _fundamental_ to this profession. Consistent APIs are _fundamental_ to this profession. Category theory--_not_ fundamental. Nice to have, and if someone points me to good tutorials on cat theory and alg data types I'll go through them--but hey, I'm unemployed.
There is a very funny/sad book called "Night Watch" by Terry Pratchett that talks about how, if political revolution isn't accepted by the people, then the obvious next step is that you need to change the people. I sense some amount of that feeling around Scala--"if people don't see the brilliance of Scala, then the people need to be changed." Well, people do see a lot of the brilliance of Scala, and that's great; but enums are something the keep coming up, which should make us think not, "how do we change people", but, "how do we do enums properly in Scala in a way that will be accepted by the audience we are aiming at.
Oh and I'm serious about the tutorials, so please feel free to provide links.
Ken




--
Daniel C. Sobral

I travel to the future all the time.
ichoran
Joined: 2009-08-14,
User offline. Last seen 2 years 3 weeks ago.
Re: java enums more compact, flexible and obvious than scala's


On Tue, Jun 28, 2011 at 12:54 PM, Ken McDonald <ykkenmcd [at] gmail [dot] com> wrote:
> > I don't personally find responses along the lines of, "learn
> > category theory" and, "you should understand algebra" either leads
> > anyone towards enlightenment or welcomes them into the scala
> > community.

These things are _fundamental_ to this profession. If you won't learn
them, you don't deserve the attribute "professional."


Um, no, they are not. There are a great many true professionals out there writing fantastic, tight, reliable code, who don't have a clue what category theory or algebraic data types are.

Indeed.  Yet, they are nonetheless cleverly re-inventing concepts from category theory (or are using concepts that category theory explains elegantly), or, in failing to re-invent the concepts, are sometimes writing less-fantastic, less-tight, less-reliable code compared to what could be done in that case.

But I don't think this means that they're not professional _programmers_.  It means they're not _category theory professionals_.  It's the same difference between being a scientist and a philosopher of science, or between being a tennis player and a sports biophysicist.  You can do the right thing--very reliably, even--without understanding, explicitly and in detail, the theory that explains why and how the thing works.  Sometimes that detailed understanding is even more of a distraction than a help (e.g. tennis--I doubt Rafael Nadal is, when swinging for a serve, thinking about tensing his muscles such that a large portion of his inertial mass is apparent to the ball upon contact with the racket).

You do have additional options for problem-solving when you understand the generalizations and theory of what you're doing, so it's useful even if not essential.

  --Rex
Ken McDonald
Joined: 2011-02-13,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's
As mentioned before, I'm certainly willing to have a go at learning category theory if someone can point me at a link (Category Theory For The Compleat Idiot would be good.) This page is getting so crowded, might be best to email me as well as posting: ykkenmcd _ at _ gmail.com.
Thanks,Ken
Seth Tisue
Joined: 2008-12-16,
User offline. Last seen 34 weeks 3 days ago.
Re: java enums more compact, flexible and obvious than scala's

On Tue, Jun 28, 2011 at 2:31 PM, Russ Paielli wrote:
> I tend to agree. Short of that, I suggest that a brief tutorial be added to
> the official Scala website explaining how best to implement enums. If one is
> already there, please tell me where to find it. When I google "scala enums,"
> all I see is some random discussion. Sure, some of it is helpful, and I was
> able to get the information I needed, but it seems to me that there should
> be something more polished out there than some rambling, unedited online
> discussion, frozen in time, complete with typos. Is that reasonable?

Stack Overflow is 10x better for this kind of thing than Google searches.

(Something on the Scala site might be nice too; not dismissing the suggestion.)

Jan van der Vorst
Joined: 2011-06-02,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

Today I studied Category Theory and I think I just might come up with
a Scala Enumeration type that is almost identical to something very
similar to Java's, and with Category Theory of course.

On Jun 28, 9:20 pm, Ken McDonald wrote:
> As mentioned before, I'm certainly willing to have a go at learning category
> theory if someone can point me at a link (Category Theory For The Compleat
> Idiot would be good.) This page is getting so crowded, might be best to
> email me as well as posting: ykkenmcd _ at _ gmail.com.
>
> Thanks,
> Ken

vpatryshev
Joined: 2009-02-16,
User offline. Last seen 1 year 24 weeks ago.
Re: java enums more compact, flexible and obvious than scala's

On Mon, Jun 27, 2011 at 8:40 AM, Randall R Schulz <rschulz [at] sonic [dot] net> wrote:
On Monday 27 June 2011, Clint Gilbert wrote:
> This is very true.  Learning category theory and understanding
> algebra are definitely good things, but those sorts of reponses are
> very off-putting to newcomers, and aren't very helpful in the short-
> or medium-term.
>
> On 06/27/2011 08:25 AM, Matthew Pocock wrote:
> > I don't personally find responses along the lines of, "learn
> > category theory" and, "you should understand algebra" either leads
> > anyone towards enlightenment or welcomes them into the scala
> > community.

These things are _fundamental_ to this profession. If you won't learn
them, you don't deserve the attribute "professional."

And I feel that Scala is a tool for professionals, not dilettants. You
don't have to know all these things to start to use it, but you should
be willing to learn in order to understand why things are as they are
and to be able to create sound artifacts.

The reason computer systems are so hideously unreliable and error-prone
today is exactly 'cause so many of its paid, putatively professional
practitioners are ignorant of these principles. The sooner we put our
understanding on a sound formal groundwork, the sooner we can get
reliable information systems to the world.

I heard myself from Guido van Rossum that he does not know category theory and is not planning to learn it.

Python may be <inject your expletive here>-prone, but you can't say Guido is not a professional, eh?

-Vlad
Joshua.Suereth
Joined: 2008-09-02,
User offline. Last seen 32 weeks 5 days ago.
Re: java enums more compact, flexible and obvious than scala's

be careful what you wish for ;)

On Jun 28, 2011 2:41 PM, "Daniel Sobral" <dcsobral [at] gmail [dot] com> wrote:
> 1. Where are the unicorns?
> 2. Where are the kittens?
> 3. Can I have a poney?
>
> On Tue, Jun 28, 2011 at 14:46, Josh Suereth <joshua [dot] suereth [at] gmail [dot] com>wrote:
>
>> Even better...
>>
>> [image: scala-lang-place-for-friends.png]
>>
>>
>> On Tue, Jun 28, 2011 at 12:54 PM, Ken McDonald <ykkenmcd [at] gmail [dot] com> wrote:
>>
>>> > On 06/27/2011 08:25 AM, Matthew Pocock wrote:
>>>> > > I don't personally find responses along the lines of, "learn
>>>> > > category theory" and, "you should understand algebra" either leads
>>>> > > anyone towards enlightenment or welcomes them into the scala
>>>> > > community.
>>>>
>>>> These things are _fundamental_ to this profession. If you won't learn
>>>> them, you don't deserve the attribute "professional."
>>>>
>>>>
>>>> Um, no, they are not. There are a great many true professionals out there
>>> writing fantastic, tight, reliable code, who don't have a clue what category
>>> theory or algebraic data types are. I worked for a company (Be Inc.) that
>>> was filled with them, and I read their code. Unit testing is _fundamental_
>>> to this profession. Consistent APIs are _fundamental_ to this profession.
>>> Category theory--_not_ fundamental. Nice to have, and if someone points me
>>> to good tutorials on cat theory and alg data types I'll go through them--but
>>> hey, I'm unemployed.
>>>
>>> There is a very funny/sad book called "Night Watch" by Terry Pratchett
>>> that talks about how, if political revolution isn't accepted by the people,
>>> then the obvious next step is that you need to change the people. I sense
>>> some amount of that feeling around Scala--"if people don't see the
>>> brilliance of Scala, then the people need to be changed." Well, people do
>>> see a lot of the brilliance of Scala, and that's great; but enums are
>>> something the keep coming up, which should make us think not, "how do we
>>> change people", but, "how do we do enums properly in Scala in a way that
>>> will be accepted by the audience we are aiming at.
>>>
>>> Oh and I'm serious about the tutorials, so please feel free to provide
>>> links.
>>>
>>> Ken
>>>
>>
>>
>
>
> --
> Daniel C. Sobral
>
> I travel to the future all the time.
dcsobral
Joined: 2009-04-23,
User offline. Last seen 38 weeks 5 days ago.
Re: java enums more compact, flexible and obvious than scala's

http://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theo...
http://www.cs.toronto.edu/~sme/presentations/cat101.pdf

On Tue, Jun 28, 2011 at 16:20, Ken McDonald wrote:
> As mentioned before, I'm certainly willing to have a go at learning category
> theory if someone can point me at a link (Category Theory For The Compleat
> Idiot would be good.) This page is getting so crowded, might be best to
> email me as well as posting: ykkenmcd _ at _ gmail.com.
> Thanks,
> Ken

mond ray mond
Joined: 2011-03-31,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's
I started down this route but hit a generalisation problem ... [ queue storm of told you so's .... ]
Following advice so far, and a little riffing we have:
package mapping
trait Enumerating {  def values: List[SomethingWithSize]}
trait SomethingWithSize {  def size: Int}
sealed abstract case class FieldMap(size: Int) extends SomethingWithSize
// 1st Instance (I want to be able to be able to pass these Enumerating "types" into functions)object FieldMap1 extends Enumerating {  def values = List[SomethingWithSize](FieldMap1Items.Field1, FieldMap1Items.Field2, FieldMap1Items.Field3)
  object FieldMap1Items {    case object Field1 extends FieldMap(3)    case object Field2 extends FieldMap(3)    case object Field3 extends FieldMap(3)  }}
When doing a fairly standard recursive call, I run out of road:
  def convertStringToMap(input: String, mappings: Enumerating) : Map[SomethingWithSize, String] = {    val mapping = mappings.values.head
    if (mapping.size > input.length())      throw new IllegalArgumentException("Trying to access beyond the end of the remaining input \"" + input + "\" with size of " + mapping.size)
    val stringValue = input.substring(0, mapping.size)
    val result = ListMap(mapping -> stringValue)
    if (mappings.values.tail.isEmpty)      result    else      result ++ convertStringToMap(input.substring(mapping.size), mappings.values.tail)  }
error: type mismatch;found   : List[mapping.SomethingWithSize]required: mapping.Enumeratingresult ++ convertStringToMap(input.substring(mapping.size), mappings.values.tail)
I could just use a List[SomethingWithSize] as a parameter but then I lose the enum concept (I feel like I am losing it already!).  I could also remove the recursion.  Anybody got any nice high order function ideas that could work here?
All ideas welcome?
Thanks
Ray
Adam Jorgensen
Joined: 2011-04-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: java enums more compact, flexible and obvious than scal
Just to add my two cents to raging discussion.
My current day-job involves writing Python code. As some of you may know, there are no built-in constructs for enums in Python. Hell, there aren't even any built-in constructs for performing switch statements.
While the lack of the former hasn't affected me much, the lack of the latter is rather irrtating. Nevertheless,if one needs something enum-like or something switch-like there are options and the lack of built-ins hasn't killed anyone.
What I'm trying to say is that coming from Java it might seem that X (X being enums in this case) is a vital language construct given that it exists in Java. Nevertheless, this is not truly the case.
Scala is not Java. Some differences might irritate or frustrate, some might make you dance with happiness.Nevertheless, it's unlike any of them are going to cost you your job or sanity...
On a final note, I think it's interesting to see what solutions people have put together on their own forEnum-like support. While it's nice for a language to have feature X built-in, it's also cool to see what people do when feature X is not built-in, especially if the language is one like Scala where there are so manypossibilities...
Adam Jorgensen
Joined: 2011-04-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: java enums more compact, flexible and obvious than scal
As for category theory and professionalism...
Professional Computer Scientist or Professional Developer?
Before you leap, there is a difference and it's not as simple as: Computer Scientist > CS Grad Developer > Non-CS Grad Developer
vpatryshev
Joined: 2009-02-16,
User offline. Last seen 1 year 24 weeks ago.
Re: Re: java enums more compact, flexible and obvious than scal
That's way beyond the topic of enums in scala... I wonder if we could start another thread, comparing, say, people with medical or musical or architectural education doing software development... believe me, some of them are amazing.
Thanks,
-Vlad


On Tue, Jun 28, 2011 at 9:33 PM, Adam Jorgensen <adam.jorgensen.za@gmail.com> wrote:
As for category theory and professionalism...
Professional Computer Scientist or Professional Developer?
Before you leap, there is a difference and it's not as simple as: Computer Scientist > CS Grad Developer > Non-CS Grad Developer

sross
Joined: 2011-06-29,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

This may be a stupid question as I am quite new to scala, but why is
everyone steering away from extending the Val class in Enumeration to
add properties?

eg.

object Planet extends Enumeration {
protected case class Val(name: String, val mass: Double, val
radius: Double) extends super.Val(nextId, name) {
def surfaceGravity: Double = Planet.G * mass / (radius * radius)
def surfaceWeight(otherMass: Double): Double = otherMass *
surfaceGravity
}
implicit def valueToPlanetVal(x: Value) = x.asInstanceOf[Val]

val G: Double = 6.67300E-11
val Mercury = Val("Mercury", 3.303e+23, 2.4397e6)
val Venus = Val("Venus", 4.869e+24, 6.0518e6)
val Earth = Val("Earth", 5.976e+24, 6.37814e6)
val Mars = Val("Mars", 6.421e+23, 3.3972e6)
val Jupiter = Val("Jupiter", 1.9e+27, 7.1492e7)
val Saturn = Val("Saturn", 5.688e+26, 6.0268e7)
val Uranus = Val("Uranus", 8.686e+25, 2.5559e7)
val Neptune = Val("Neptune", 1.024e+26, 2.4746e7)
}

scala> Planet.values.filter(_.radius > 7.0e6)
res16: Planet.ValueSet = Planet.ValueSet(Jupiter, Saturn, Uranus,
Neptune)

Cheers,
Sean.

On Jun 28, 12:41 am, richard emberson
wrote:
> I based the Enum class I use on the Sgine's Enum class,
>      http://code.google.com/p/sgine/
>
> It lets one do stuff like:
>
> sealed abstract class Status extends Status.Value
> object Status extends Enum[Status] {
>    case object Off   extends Status
>    case object On    extends Status
>
>    Status(Off, On)
>
> }
>
> sealed abstract class Planet(name: String,
>                               val mass: Double,
>                               val radius: Double)
>       extends Planet.Value(name) {
>    def surfaceGravity: Double = Planet.G * mass / (radius * radius)
>    def surfaceWeight(otherMass: Double): Double = otherMass * surfaceGravity}
>
> object Planet extends Enum[Planet] {
>    // universal gravitational constant(m3 kg-1 s-2)
>    val G: Double = 6.67300E-11
>
>    object Mercury   extends Planet("Mercury", 3.303e+23, 2.4397e6)
>    object Venus     extends Planet("Venus", 4.869e+24, 6.0518e6)
>    object Earth     extends Planet("Earth", 5.976e+24, 6.37814e6)
>    object Mars      extends Planet("Mars", 6.421e+23, 3.3972e6)
>    object Jupiter   extends Planet("Jupitier", 1.9e+27, 7.1492e7)
>    object Saturn    extends Planet("Saturn", 5.688e+26, 6.0268e7)
>    object Uranus    extends Planet("Uranus", 8.686e+25, 2.5559e7)
>    object Neptune   extends Planet("Neptune", 1.024e+26, 2.4746e7)
>
>    Planet(Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune)
>
> }
>
> Yea, you have to create a sealed class and object and you
> have to register the enum members, but it gives me what I want.
>
> Also, in my modified version I do not get the "MODULE$" field
> of the enum class (but, as a result, mine is not quite as a clean as
> the Sgine version).
>
> Richard
>
> On 06/27/2011 04:06 PM, john sullivan wrote:
>
> > Your feedback? This is what I do now instead of Java enums. It might not
> > be the best approach, but it's what I came up with.
>
> >http://scabl.blogspot.com/2011/06/scala-enums.html
>
> --
> Quis custodiet ipsos custodes

Jan van der Vorst
Joined: 2011-06-02,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

// This implementation of an Enumeration allows you to add properties
to an Enumeration.

abstract class MyEnumeration {
// "Value" must be the name of the class defining your values
type Value

// Contains your values in definition order
private var vals = collection.IndexedSeq[Value]()

// A mixin for your values class to automatically collect the values
protected trait ValuesCollector { self: Value =>
vals = vals :+ self
}

def apply(ordinal: Int) = vals(ordinal)

def values = vals
}

// The example that started this discussion

object FlatFileHeaderMapping extends MyEnumeration {
final case class Value private[FlatFileHeaderMapping](val name:
String, val size: Int) extends ValuesCollector {
override def toString = name
}

val Field1 = Value("Field1", 1)
val Field2 = Value("Field2", 5)
val Field3 = Value("Field3", 4)
}

object LegacyRecordProcessor {
def processLegacyRecord(inputString: String):
Map[FlatFileHeaderMapping.Value, String] = {
var end = 0
FlatFileHeaderMapping.values map { fld =>
val start = end
end += fld.size
(fld, inputString.substring(start, end))
} toMap
}
// Test
def main(args: Array[String]) {
println(processLegacyRecord("Hello World")) // Map(Field1 -> H,
Field2 -> ello , Field3 -> Worl)
}
}

On Jun 29, 10:42 am, sross wrote:
> This may be a stupid question as I am quite new to scala, but why is
> everyone steering away from extending the Val class in Enumeration to
> add properties?
>
> eg.
>
> object Planet extends Enumeration {
>    protected case class Val(name: String, val mass: Double, val
> radius: Double) extends super.Val(nextId, name) {
>      def surfaceGravity: Double = Planet.G * mass / (radius * radius)
>      def surfaceWeight(otherMass: Double): Double = otherMass *
> surfaceGravity
>    }
>    implicit def valueToPlanetVal(x: Value) = x.asInstanceOf[Val]
>
>    val G: Double = 6.67300E-11
>    val Mercury = Val("Mercury", 3.303e+23, 2.4397e6)
>    val Venus   = Val("Venus", 4.869e+24, 6.0518e6)
>    val Earth   = Val("Earth", 5.976e+24, 6.37814e6)
>    val Mars    = Val("Mars", 6.421e+23, 3.3972e6)
>    val Jupiter = Val("Jupiter", 1.9e+27, 7.1492e7)
>    val Saturn  = Val("Saturn", 5.688e+26, 6.0268e7)
>    val Uranus  = Val("Uranus", 8.686e+25, 2.5559e7)
>    val Neptune = Val("Neptune", 1.024e+26, 2.4746e7)
>
> }
>
> scala> Planet.values.filter(_.radius > 7.0e6)
> res16: Planet.ValueSet = Planet.ValueSet(Jupiter, Saturn, Uranus,
> Neptune)
>
> Cheers,
>  Sean.
>
> On Jun 28, 12:41 am, richard emberson
> wrote:
>
>
>
> > I based the Enum class I use on the Sgine's Enum class,
> >      http://code.google.com/p/sgine/
>
> > It lets one do stuff like:
>
> > sealed abstract class Status extends Status.Value
> > object Status extends Enum[Status] {
> >    case object Off   extends Status
> >    case object On    extends Status
>
> >    Status(Off, On)
>
> > }
>
> > sealed abstract class Planet(name: String,
> >                               val mass: Double,
> >                               val radius: Double)
> >       extends Planet.Value(name) {
> >    def surfaceGravity: Double = Planet.G * mass / (radius * radius)
> >    def surfaceWeight(otherMass: Double): Double = otherMass * surfaceGravity}
>
> > object Planet extends Enum[Planet] {
> >    // universal gravitational constant(m3 kg-1 s-2)
> >    val G: Double = 6.67300E-11
>
> >    object Mercury   extends Planet("Mercury", 3.303e+23, 2.4397e6)
> >    object Venus     extends Planet("Venus", 4.869e+24, 6.0518e6)
> >    object Earth     extends Planet("Earth", 5.976e+24, 6.37814e6)
> >    object Mars      extends Planet("Mars", 6.421e+23, 3.3972e6)
> >    object Jupiter   extends Planet("Jupitier", 1.9e+27, 7.1492e7)
> >    object Saturn    extends Planet("Saturn", 5.688e+26, 6.0268e7)
> >    object Uranus    extends Planet("Uranus", 8.686e+25, 2.5559e7)
> >    object Neptune   extends Planet("Neptune", 1.024e+26, 2.4746e7)
>
> >    Planet(Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune)
>
> > }
>
> > Yea, you have to create a sealed class and object and you
> > have to register the enum members, but it gives me what I want.
>
> > Also, in my modified version I do not get the "MODULE$" field
> > of the enum class (but, as a result, mine is not quite as a clean as
> > the Sgine version).
>
> > Richard
>
> > On 06/27/2011 04:06 PM, john sullivan wrote:
>
> > > Your feedback? This is what I do now instead of Java enums. It might not
> > > be the best approach, but it's what I came up with.
>
> > >http://scabl.blogspot.com/2011/06/scala-enums.html
>
> > --
> > Quis custodiet ipsos custodes- Hide quoted text -
>
> - Show quoted text -

Jan van der Vorst
Joined: 2011-06-02,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

See how you can add bahaviour as well:

object Planet extends MyEnumeration {

case class Value(val name: String, val mass: Double, val radius:
Double) extends ValuesCollector {
override def toString = name

// universal gravitational constant (m3 kg-1 s-2)
private val G = 6.67300E-11;

def surfaceGravity = G * mass / (radius * radius)
def surfaceWeight(otherMass: Double) = otherMass * surfaceGravity

}

val MERCURY = Value("MERCURY", 3.303e+23, 2.4397e6)
val VENUS = Value("VENUS", 4.869e+24, 6.0518e6)
val EARTH = Value("EARTH", 5.976e+24, 6.37814e6)
val MARS = Value("MARS", 6.421e+23, 3.3972e6)
val JUPITER = Value("JUPITER", 1.9e+27, 7.1492e7)
val SATURN = Value("SATURN", 5.688e+26, 6.0268e7)
val URANUS = Value("URANUS", 8.686e+25, 2.5559e7)
val NEPTUNE = Value("NEPTUNE", 1.024e+26, 2.4746e7)
val PLUTO = Value("PLUTO", 1.27e+22, 1.137e6)

}

object PlanetTest {
def main(args: Array[String]) {
val earthWeight = 175
val mass = earthWeight/Planet.EARTH.surfaceGravity
for (p <- Planet.values) println("Your weight on %s is %f" format
(p.name, p.surfaceWeight(mass)))
/* Your weight on MERCURY is 66.107583
* Your weight on VENUS is 158.374842
* Your weight on EARTH is 175.000000
* Your weight on MARS is 66.279007
* Your weight on JUPITER is 442.847567
* Your weight on SATURN is 186.552719
* Your weight on URANUS is 158.397260
* Your weight on NEPTUNE is 199.207413
* Your weight on PLUTO is 11.703031
*/
}
}

On Jun 29, 12:33 pm, Jan van der Vorst wrote:
> // This implementation of an Enumeration allows you to add properties
> to an Enumeration.
>
> abstract class MyEnumeration {
>   // "Value" must be the name of the class defining your values
>   type Value
>
>   // Contains your values in definition order
>   private var vals = collection.IndexedSeq[Value]()
>
>   // A mixin for your values class to automatically collect the values
>   protected trait ValuesCollector { self: Value =>
>     vals = vals :+ self
>   }
>
>   def apply(ordinal: Int) = vals(ordinal)
>
>   def values = vals
>
> }
>
> // The example that started this discussion
>
> object FlatFileHeaderMapping extends MyEnumeration {
>   final case class Value private[FlatFileHeaderMapping](val name:
> String, val size: Int) extends ValuesCollector {
>     override def toString = name
>   }
>
>   val Field1 = Value("Field1", 1)
>   val Field2 = Value("Field2", 5)
>   val Field3 = Value("Field3", 4)
>
> }
>
> object LegacyRecordProcessor {
>   def processLegacyRecord(inputString: String):
> Map[FlatFileHeaderMapping.Value, String] = {
>     var end = 0
>      FlatFileHeaderMapping.values map { fld =>
>       val start = end
>       end += fld.size
>       (fld, inputString.substring(start, end))
>     } toMap
>   }
>   // Test
>   def main(args: Array[String]) {
>      println(processLegacyRecord("Hello World")) // Map(Field1 -> H,
> Field2 -> ello , Field3 -> Worl)
>   }
>
> }
>
> On Jun 29, 10:42 am, sross wrote:
>
>
>
> > This may be a stupid question as I am quite new to scala, but why is
> > everyone steering away from extending the Val class in Enumeration to
> > add properties?
>
> > eg.
>
> > object Planet extends Enumeration {
> >    protected case class Val(name: String, val mass: Double, val
> > radius: Double) extends super.Val(nextId, name) {
> >      def surfaceGravity: Double = Planet.G * mass / (radius * radius)
> >      def surfaceWeight(otherMass: Double): Double = otherMass *
> > surfaceGravity
> >    }
> >    implicit def valueToPlanetVal(x: Value) = x.asInstanceOf[Val]
>
> >    val G: Double = 6.67300E-11
> >    val Mercury = Val("Mercury", 3.303e+23, 2.4397e6)
> >    val Venus   = Val("Venus", 4.869e+24, 6.0518e6)
> >    val Earth   = Val("Earth", 5.976e+24, 6.37814e6)
> >    val Mars    = Val("Mars", 6.421e+23, 3.3972e6)
> >    val Jupiter = Val("Jupiter", 1.9e+27, 7.1492e7)
> >    val Saturn  = Val("Saturn", 5.688e+26, 6.0268e7)
> >    val Uranus  = Val("Uranus", 8.686e+25, 2.5559e7)
> >    val Neptune = Val("Neptune", 1.024e+26, 2.4746e7)
>
> > }
>
> > scala> Planet.values.filter(_.radius > 7.0e6)
> > res16: Planet.ValueSet = Planet.ValueSet(Jupiter, Saturn, Uranus,
> > Neptune)
>
> > Cheers,
> >  Sean.
>
> > On Jun 28, 12:41 am, richard emberson
> > wrote:
>
> > > I based the Enum class I use on the Sgine's Enum class,
> > >      http://code.google.com/p/sgine/
>
> > > It lets one do stuff like:
>
> > > sealed abstract class Status extends Status.Value
> > > object Status extends Enum[Status] {
> > >    case object Off   extends Status
> > >    case object On    extends Status
>
> > >    Status(Off, On)
>
> > > }
>
> > > sealed abstract class Planet(name: String,
> > >                               val mass: Double,
> > >                               val radius: Double)
> > >       extends Planet.Value(name) {
> > >    def surfaceGravity: Double = Planet.G * mass / (radius * radius)
> > >    def surfaceWeight(otherMass: Double): Double = otherMass * surfaceGravity}
>
> > > object Planet extends Enum[Planet] {
> > >    // universal gravitational constant(m3 kg-1 s-2)
> > >    val G: Double = 6.67300E-11
>
> > >    object Mercury   extends Planet("Mercury", 3.303e+23, 2.4397e6)
> > >    object Venus     extends Planet("Venus", 4.869e+24, 6.0518e6)
> > >    object Earth     extends Planet("Earth", 5.976e+24, 6.37814e6)
> > >    object Mars      extends Planet("Mars", 6.421e+23, 3.3972e6)
> > >    object Jupiter   extends Planet("Jupitier", 1.9e+27, 7.1492e7)
> > >    object Saturn    extends Planet("Saturn", 5.688e+26, 6.0268e7)
> > >    object Uranus    extends Planet("Uranus", 8.686e+25, 2.5559e7)
> > >    object Neptune   extends Planet("Neptune", 1.024e+26, 2.4746e7)
>
> > >    Planet(Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune)
>
> > > }
>
> > > Yea, you have to create a sealed class and object and you
> > > have to register the enum members, but it gives me what I want.
>
> > > Also, in my modified version I do not get the "MODULE$" field
> > > of the enum class (but, as a result, mine is not quite as a clean as
> > > the Sgine version).
>
> > > Richard
>
> > > On 06/27/2011 04:06 PM, john sullivan wrote:
>
> > > > Your feedback? This is what I do now instead of Java enums. It might not
> > > > be the best approach, but it's what I came up with.
>
> > > >http://scabl.blogspot.com/2011/06/scala-enums.html
>
> > > --
> > > Quis custodiet ipsos custodes- Hide quoted text -
>
> > - Show quoted text -- Hide quoted text -
>
> - Show quoted text -

DaveScala
Joined: 2011-03-18,
User offline. Last seen 1 year 21 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

Well done, Sean!
This is a nice and elegant solution because it is concise, reusable
and everything is within one object.
You have good skills in OOP and know how to apply it well.
I was tinkering myself for days, it worked but ended up with
fragmented code.
I couldn't get it all inside one concise object and in the end I got
stuck with a chicken
and the egg compile problem each time, but you have saved the day.

Jan van der Vorst
Joined: 2011-06-02,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

We can even do it more concise by getting the value names through a
little refection:

abstract class MyEnumeration {
// "Value" must be the name of the class defining your values
type Value

// Contains your values in definition order
private val vals = collection.mutable.LinkedHashMap[String, Value]()

// A mixin for your values class to automatically collect the values
protected trait ValuesCollector { self: Value =>
private val ordinal = vals.size

vals += (fieldNames(ordinal) -> self)

def getName = fieldNames(ordinal)
override def toString = getName
}

def apply(ordinal: Int) = vals(fieldNames(ordinal))
def apply(fldName: String) = vals(fldName)

def values = vals.values
def namedValues: collection.Map[String, Value] = vals

// Getting the field names through reflection.
// Copied from scala.Enumeration
private val fieldNames = getClass.getMethods filter (m =>
m.getParameterTypes.isEmpty &&
classOf[ValuesCollector].isAssignableFrom(m.getReturnType) &&
m.getDeclaringClass != classOf[MyEnumeration]) map (_.getName)

}

That way we can write:
object Planet extends MyEnumeration {

case class Value(val mass: Double, val radius: Double) extends
ValuesCollector {
// universal gravitational constant (m3 kg-1 s-2)
private val G = 6.67300E-11;

def surfaceGravity = G * mass / (radius * radius)
def surfaceWeight(otherMass: Double) = otherMass * surfaceGravity

}

val MERCURY = Value(3.303e+23, 2.4397e6)
val VENUS = Value(4.869e+24, 6.0518e6)
val EARTH = Value(5.976e+24, 6.37814e6)
val MARS = Value(6.421e+23, 3.3972e6)
val JUPITER = Value(1.9e+27, 7.1492e7)
val SATURN = Value(5.688e+26, 6.0268e7)
val URANUS = Value(8.686e+25, 2.5559e7)
val NEPTUNE = Value(1.024e+26, 2.4746e7)
val PLUTO = Value(1.27e+22, 1.137e6)

}

object PlanetTest {
def main(args: Array[String]) {
val earthWeight = 175
val mass = earthWeight/Planet.EARTH.surfaceGravity
for (p <- Planet.values) println("Your weight on %s is %f" format
(p, p.surfaceWeight(mass)))
/* Your weight on MERCURY is 66.107583
* Your weight on VENUS is 158.374842
* Your weight on EARTH is 175.000000
* Your weight on MARS is 66.279007
* Your weight on JUPITER is 442.847567
* Your weight on SATURN is 186.552719
* Your weight on URANUS is 158.397260
* Your weight on NEPTUNE is 199.207413
* Your weight on PLUTO is 11.703031
*/
}
}

On Jun 29, 3:48 pm, Dave wrote:
> Well done, Sean!
> This is a nice and elegant solution because it is concise, reusable
> and everything is within one object.
> You have good skills in OOP and know how to apply it well.
> I was tinkering myself for days, it worked but ended up with
> fragmented code.
> I couldn't get it all inside one concise object and in the end I got
> stuck with a chicken
> and the egg compile problem each time, but you have saved the day.
>

Chris Marshall
Joined: 2009-06-17,
User offline. Last seen 44 weeks 3 days ago.
RE: Re: java enums more compact, flexible and obvious than scal
You should add this to the SO answer:
http://stackoverflow.com/questions/4346580/how-to-add-a-method-to-enumeration-in-scala
Chris

> Date: Wed, 29 Jun 2011 05:45:45 -0700
> Subject: [scala-user] Re: java enums more compact, flexible and obvious than scala's equivalent?
> From: ndervorst [at] gmail [dot] com
> To: scala-user [at] googlegroups [dot] com
>
> See how you can add bahaviour as well:
>
> object Planet extends MyEnumeration {
>
> case class Value(val name: String, val mass: Double, val radius:
> Double) extends ValuesCollector {
> override def toString = name
>
> // universal gravitational constant (m3 kg-1 s-2)
> private val G = 6.67300E-11;
>
> def surfaceGravity = G * mass / (radius * radius)
> def surfaceWeight(otherMass: Double) = otherMass * surfaceGravity
>
> }
>
> val MERCURY = Value("MERCURY", 3.303e+23, 2.4397e6)
> val VENUS = Value("VENUS", 4.869e+24, 6.0518e6)

DaveScala
Joined: 2011-03-18,
User offline. Last seen 1 year 21 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

I think Sean's solution should be the second usage example in
Enumeration.scala/Scaladoc.

The problem(s) I have with Jan's (last) solution is that:
- it is a duplicate functionality, a fork on Enumeration and then
modified the Enumeration class (duplicate code is hard too maintain,
avoid duplicate code what's already in the API as much as possible).
- MyEnumeration is not extending standard Scala Enumeration (where is
withName?) so it is not compatible with existing Enumeration
If someone made a framework/library that uses Enumeration, you'll have
to change that framework as well in order to use it (poor reusibility)
- it's an object and a class solution, not one object solution and the
total solution is bigger
- Pluto is not a planet

Jan van der Vorst
Joined: 2011-06-02,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

Thanks for your advise. I have posted the answer:
http://www.google.com/url?sa=D&q=http://stackoverflow.com/questions/4346...

Jan
On Jun 29, 5:25 pm, Chris Marshall wrote:
> You should add this to the SO answer:http://stackoverflow.com/questions/4346580/how-to-add-a-method-to-enu...
> Chris
>
> > Date: Wed, 29 Jun 2011 05:45:45 -0700
> > Subject: [scala-user] Re: java enums more compact, flexible and obvious than scala's equivalent?
> > From: ndervo [dot] [dot] [dot] [at] gmail [dot] com
> > To: scala-user [at] googlegroups [dot] com
>
> > See how you can add bahaviour as well:
>
> > object Planet extends MyEnumeration {
>
> >   case class Value(val name: String, val mass: Double, val radius:
> > Double) extends ValuesCollector {
> >     override def toString = name
>
> >     // universal gravitational constant  (m3 kg-1 s-2)
> >     private val G = 6.67300E-11;
>
> >     def surfaceGravity = G * mass / (radius * radius)
> >     def surfaceWeight(otherMass: Double) = otherMass * surfaceGravity
>
> >   }
>
> >   val MERCURY = Value("MERCURY", 3.303e+23, 2.4397e6)
> >   val VENUS = Value("VENUS", 4.869e+24, 6.0518e6)

Jan van der Vorst
Joined: 2011-06-02,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

Well, it was an interesting exercise. I agree with all points.

On Jun 29, 7:34 pm, Dave wrote:
> I think Sean's solution should be the second usage example in
> Enumeration.scala/Scaladoc.
>
> The problem(s) I have with Jan's (last) solution is that:
> - it is a duplicate functionality, a fork on Enumeration and then
> modified the Enumeration class (duplicate code is hard too maintain,
> avoid duplicate code what's already in the API as much as possible).
> - MyEnumeration is not extending standard Scala Enumeration  (where is
> withName?) so it is not compatible with existing Enumeration
> If someone made a framework/library that uses Enumeration, you'll have
> to change that framework as well in order to use it (poor reusibility)
> - it's an object and a class solution, not one object solution and the
> total solution is bigger
> - Pluto is not a planet

mond ray mond
Joined: 2011-03-31,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's

The group is cookin. Bizarrely, I live on Jan van der Vorstlaan ;-)

On Wednesday, 29 June 2011, Jan van der Vorst wrote:
> Well, it was an interesting exercise. I agree with all points.
>
> On Jun 29, 7:34 pm, Dave wrote:
>> I think Sean's solution should be the second usage example in
>> Enumeration.scala/Scaladoc.
>>
>> The problem(s) I have with Jan's (last) solution is that:
>> - it is a duplicate functionality, a fork on Enumeration and then
>> modified the Enumeration class (duplicate code is hard too maintain,
>> avoid duplicate code what's already in the API as much as possible).
>> - MyEnumeration is not extending standard Scala Enumeration  (where is
>> withName?) so it is not compatible with existing Enumeration
>> If someone made a framework/library that uses Enumeration, you'll have
>> to change that framework as well in order to use it (poor reusibility)
>> - it's an object and a class solution, not one object solution and the
>> total solution is bigger
>> - Pluto is not a planet

sullivan-
Joined: 2009-10-13,
User offline. Last seen 39 weeks 5 days ago.
Re: Re: java enums more compact, flexible and obvious than scal
I agree. Sean's response is perfect for people who simply want to emulate Java enumerations. I wish I had seen such an example a few months back!

On Wed, Jun 29, 2011 at 1:34 PM, Dave <dave [dot] mahabiersing [at] hotmail [dot] com> wrote:
I think Sean's solution should be the second usage example in
Enumeration.scala/Scaladoc.
dcsobral
Joined: 2009-04-23,
User offline. Last seen 38 weeks 5 days ago.
Re: Re: java enums more compact, flexible and obvious than scal

On Wed, Jun 29, 2011 at 14:31, Jan van der Vorst wrote:
> Thanks for your advise. I have posted the answer:
> http://www.google.com/url?sa=D&q=http://stackoverflow.com/questions/4346...

This is not Sean's solution. Sean's solution just extends Value.

>
> Jan
> On Jun 29, 5:25 pm, Chris Marshall wrote:
>> You should add this to the SO answer:http://stackoverflow.com/questions/4346580/how-to-add-a-method-to-enu...
>> Chris
>>
>> > Date: Wed, 29 Jun 2011 05:45:45 -0700
>> > Subject: [scala-user] Re: java enums more compact, flexible and obvious than scala's equivalent?
>> > From: ndervo [dot] [dot] [dot] [at] gmail [dot] com
>> > To: scala-user [at] googlegroups [dot] com
>>
>> > See how you can add bahaviour as well:
>>
>> > object Planet extends MyEnumeration {
>>
>> >   case class Value(val name: String, val mass: Double, val radius:
>> > Double) extends ValuesCollector {
>> >     override def toString = name
>>
>> >     // universal gravitational constant  (m3 kg-1 s-2)
>> >     private val G = 6.67300E-11;
>>
>> >     def surfaceGravity = G * mass / (radius * radius)
>> >     def surfaceWeight(otherMass: Double) = otherMass * surfaceGravity
>>
>> >   }
>>
>> >   val MERCURY = Value("MERCURY", 3.303e+23, 2.4397e6)
>> >   val VENUS = Value("VENUS", 4.869e+24, 6.0518e6)

richard emberson
Joined: 2010-03-22,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: java enums more compact, flexible and obvious than scal

The following compiles just fine:

def test(e: Planet.Value): Unit = {
e match {
case Planet.Mercury => println("Mercury")
}
}

but calling

test(Planet.Venus)

from Main at runtime yields:

scala.MatchError: Venus (of class Planet$Val)
at Main$.test(Enum.scala:25)
at Main$.main(Enum.scala:31)
.......

I prefer to an an Enum where one gets a compile-time error
rather than a run-time error.
And, if one adds

case _ =>

to the match statement, then when Pluto becomes a Planet again,
the compiler will not tell you nor will you get a run-time error,
but the code for all match-statements is still wrong.

On 06/29/2011 01:42 AM, sross wrote:
> This may be a stupid question as I am quite new to scala, but why is
> everyone steering away from extending the Val class in Enumeration to
> add properties?
>
> eg.
>
> object Planet extends Enumeration {
> protected case class Val(name: String, val mass: Double, val
> radius: Double) extends super.Val(nextId, name) {
> def surfaceGravity: Double = Planet.G * mass / (radius * radius)
> def surfaceWeight(otherMass: Double): Double = otherMass *
> surfaceGravity
> }
> implicit def valueToPlanetVal(x: Value) = x.asInstanceOf[Val]
>
> val G: Double = 6.67300E-11
> val Mercury = Val("Mercury", 3.303e+23, 2.4397e6)
> val Venus = Val("Venus", 4.869e+24, 6.0518e6)
> val Earth = Val("Earth", 5.976e+24, 6.37814e6)
> val Mars = Val("Mars", 6.421e+23, 3.3972e6)
> val Jupiter = Val("Jupiter", 1.9e+27, 7.1492e7)
> val Saturn = Val("Saturn", 5.688e+26, 6.0268e7)
> val Uranus = Val("Uranus", 8.686e+25, 2.5559e7)
> val Neptune = Val("Neptune", 1.024e+26, 2.4746e7)
> }
>
>
> scala> Planet.values.filter(_.radius> 7.0e6)
> res16: Planet.ValueSet = Planet.ValueSet(Jupiter, Saturn, Uranus,
> Neptune)
>
>
> Cheers,
> Sean.
>
>
> On Jun 28, 12:41 am, richard emberson
> wrote:
>> I based the Enum class I use on the Sgine's Enum class,
>> http://code.google.com/p/sgine/
>>
>> It lets one do stuff like:
>>
>> sealed abstract class Status extends Status.Value
>> object Status extends Enum[Status] {
>> case object Off extends Status
>> case object On extends Status
>>
>> Status(Off, On)
>>
>> }
>>
>> sealed abstract class Planet(name: String,
>> val mass: Double,
>> val radius: Double)
>> extends Planet.Value(name) {
>> def surfaceGravity: Double = Planet.G * mass / (radius * radius)
>> def surfaceWeight(otherMass: Double): Double = otherMass * surfaceGravity}
>>
>> object Planet extends Enum[Planet] {
>> // universal gravitational constant(m3 kg-1 s-2)
>> val G: Double = 6.67300E-11
>>
>> object Mercury extends Planet("Mercury", 3.303e+23, 2.4397e6)
>> object Venus extends Planet("Venus", 4.869e+24, 6.0518e6)
>> object Earth extends Planet("Earth", 5.976e+24, 6.37814e6)
>> object Mars extends Planet("Mars", 6.421e+23, 3.3972e6)
>> object Jupiter extends Planet("Jupitier", 1.9e+27, 7.1492e7)
>> object Saturn extends Planet("Saturn", 5.688e+26, 6.0268e7)
>> object Uranus extends Planet("Uranus", 8.686e+25, 2.5559e7)
>> object Neptune extends Planet("Neptune", 1.024e+26, 2.4746e7)
>>
>> Planet(Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune)
>>
>> }
>>
>> Yea, you have to create a sealed class and object and you
>> have to register the enum members, but it gives me what I want.
>>
>> Also, in my modified version I do not get the "MODULE$" field
>> of the enum class (but, as a result, mine is not quite as a clean as
>> the Sgine version).
>>
>> Richard
>>
>> On 06/27/2011 04:06 PM, john sullivan wrote:
>>
>>> Your feedback? This is what I do now instead of Java enums. It might not
>>> be the best approach, but it's what I came up with.
>>
>>> http://scabl.blogspot.com/2011/06/scala-enums.html
>>
>> --
>> Quis custodiet ipsos custodes
>

Jan van der Vorst
Joined: 2011-06-02,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

I don't think this has to do with the Enum version.

On Jun 29, 10:30 pm, richard emberson
wrote:
> The following compiles just fine:
>
>    def test(e: Planet.Value): Unit = {
>      e match {
>        case Planet.Mercury => println("Mercury")
>      }
>    }
>
> but calling
>
> test(Planet.Venus)
>
> from Main at runtime yields:
>
> scala.MatchError: Venus (of class Planet$Val)
>          at Main$.test(Enum.scala:25)
>          at Main$.main(Enum.scala:31)
>     .......
>
> I prefer to an an Enum where one gets a compile-time error
> rather than a run-time error.
> And, if one adds
>
>    case _ =>
>
> to the match statement, then when Pluto becomes a Planet again,
> the compiler will not tell you nor will you get a run-time error,
> but the code for all match-statements is still wrong.
>
> On 06/29/2011 01:42 AM, sross wrote:
>
>
>
> > This may be a stupid question as I am quite new to scala, but why is
> > everyone steering away from extending the Val class in Enumeration to
> > add properties?
>
> > eg.
>
> > object Planet extends Enumeration {
> >     protected case class Val(name: String, val mass: Double, val
> > radius: Double) extends super.Val(nextId, name) {
> >       def surfaceGravity: Double = Planet.G * mass / (radius * radius)
> >       def surfaceWeight(otherMass: Double): Double = otherMass *
> > surfaceGravity
> >     }
> >     implicit def valueToPlanetVal(x: Value) = x.asInstanceOf[Val]
>
> >     val G: Double = 6.67300E-11
> >     val Mercury = Val("Mercury", 3.303e+23, 2.4397e6)
> >     val Venus   = Val("Venus", 4.869e+24, 6.0518e6)
> >     val Earth   = Val("Earth", 5.976e+24, 6.37814e6)
> >     val Mars    = Val("Mars", 6.421e+23, 3.3972e6)
> >     val Jupiter = Val("Jupiter", 1.9e+27, 7.1492e7)
> >     val Saturn  = Val("Saturn", 5.688e+26, 6.0268e7)
> >     val Uranus  = Val("Uranus", 8.686e+25, 2.5559e7)
> >     val Neptune = Val("Neptune", 1.024e+26, 2.4746e7)
> > }
>
> > scala>  Planet.values.filter(_.radius>  7.0e6)
> > res16: Planet.ValueSet = Planet.ValueSet(Jupiter, Saturn, Uranus,
> > Neptune)
>
> > Cheers,
> >   Sean.
>
> > On Jun 28, 12:41 am, richard emberson
> > wrote:
> >> I based the Enum class I use on the Sgine's Enum class,
> >>      http://code.google.com/p/sgine/
>
> >> It lets one do stuff like:
>
> >> sealed abstract class Status extends Status.Value
> >> object Status extends Enum[Status] {
> >>     case object Off   extends Status
> >>     case object On    extends Status
>
> >>     Status(Off, On)
>
> >> }
>
> >> sealed abstract class Planet(name: String,
> >>                                val mass: Double,
> >>                                val radius: Double)
> >>        extends Planet.Value(name) {
> >>     def surfaceGravity: Double = Planet.G * mass / (radius * radius)
> >>     def surfaceWeight(otherMass: Double): Double = otherMass * surfaceGravity}
>
> >> object Planet extends Enum[Planet] {
> >>     // universal gravitational constant(m3 kg-1 s-2)
> >>     val G: Double = 6.67300E-11
>
> >>     object Mercury   extends Planet("Mercury", 3.303e+23, 2.4397e6)
> >>     object Venus     extends Planet("Venus", 4.869e+24, 6.0518e6)
> >>     object Earth     extends Planet("Earth", 5.976e+24, 6.37814e6)
> >>     object Mars      extends Planet("Mars", 6.421e+23, 3.3972e6)
> >>     object Jupiter   extends Planet("Jupitier", 1.9e+27, 7.1492e7)
> >>     object Saturn    extends Planet("Saturn", 5.688e+26, 6.0268e7)
> >>     object Uranus    extends Planet("Uranus", 8.686e+25, 2.5559e7)
> >>     object Neptune   extends Planet("Neptune", 1.024e+26, 2.4746e7)
>
> >>     Planet(Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune)
>
> >> }
>
> >> Yea, you have to create a sealed class and object and you
> >> have to register the enum members, but it gives me what I want.
>
> >> Also, in my modified version I do not get the "MODULE$" field
> >> of the enum class (but, as a result, mine is not quite as a clean as
> >> the Sgine version).
>
> >> Richard
>
> >> On 06/27/2011 04:06 PM, john sullivan wrote:
>
> >>> Your feedback? This is what I do now instead of Java enums. It might not
> >>> be the best approach, but it's what I came up with.
>
> >>>http://scabl.blogspot.com/2011/06/scala-enums.html
>
> >> --
> >> Quis custodiet ipsos custodes
>
> --
> Quis custodiet ipsos custodes

DaveScala
Joined: 2011-03-18,
User offline. Last seen 1 year 21 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

But that is normal pattern matching behaviour. It has nothing to do
with enumerations.
Like this simple example, it compiles fine but in runtime it 's an
error which it should do because 3 cannot go anywhere:

package patternmatching

object Main extends App {

def test(n: Int) = n match {
case 1 => println(n)
case 2 => println(n)
}

test(1)
test(2)
test(3)
}
Output
1
2
scala.MatchError: 3 (of class java.lang.Integer)

If Pluto becomes a Planet again then you should adjust and recompile
your enumeration again and you add also a case for Planet.Pluto in
your main application.

If you want to make the design more flexible then you should
reconsider your design and use for instance an astronomical object
name enumeration object with values earth, sun, mars, venus, pluto etc
and a astronomical object type enumeration object with star, planet,
dwarf planet, asteroid, etc as a property on that astronomical object
name or vice versa depending on what you are doing.

Another option is to store the data that might change frequently in a
database and build a user interface to change the settings.

Enumerations are good for a known set of data that are unlikely to
change much and thus can be hard-coded in the software.

A good design decision is still important with Scala, Scala doesn't
make a poor design better.

Combining the WeekDay and the Planet enumeration examples:

package dualenums

object AOCategory extends Enumeration ("Star", "Planet",
"Dwarfplanet", "Asteroid"){
type AOCategory = Value
val STAR, PLANET, DWARFPLANET, ASTEROID = Value
}

object AstronomicalObject extends Enumeration {
import AOCategory._ //importing the type AOCategory
protected case class Val(name: String, val category: AOCategory)
extends super.Val(nextId, name)
implicit def valueToAstronomicalObjectVal(x: Value) =
x.asInstanceOf[Val]
type AstronomicalObject = Value
val SUN = Val("Sun", STAR)
val MERCURY = Val("Mercury", PLANET)
val VENUS = Val("Venus", PLANET)
val EARTH = Val("Earth", PLANET)
val MARS = Val("Mars", PLANET)
val JUPITER = Val("Jupiter", PLANET)
val SATURN = Val("Saturn", PLANET)
val URANUS = Val("Uranus", PLANET)
val NEPTUNE = Val("Neptune", PLANET)
val PLUTO = Val("Pluto", DWARFPLANET)
}

object Main extends App {

import AstronomicalObject._ //importing the type
AstronomicalObject
def test(ao: AstronomicalObject) = ao.category match {
case AOCategory.STAR => println(ao.name + "
is a star!")
case AOCategory.PLANET => println(ao.name +
" is a planet!")
case AOCategory.DWARFPLANET =>
println(ao.name + " is a dwarfplanet!")
case AOCategory.ASTEROID => println(ao.name
+ " is a asteroid!")
case _ => println("Unknown object " + ao.name
+ " found!")
}

for(ao <- AstronomicalObject.values) test(ao)
// withName is case-sensitive, typo means
java.util.NoSuchElementException: None.get
println("Earth is a " +
AstronomicalObject.withName("Earth").category)
println("Category star is " + AOCategory.withName("Star"))
println("Finding all dwarfplanets:")
AstronomicalObject.values.filter(_.category ==
AOCategory.DWARFPLANET).foreach(println)
}

Output:
Sun is a star!
Mercury is a planet!
Venus is a planet!
Earth is a planet!
Mars is a planet!
Jupiter is a planet!
Saturn is a planet!
Uranus is a planet!
Neptune is a planet!
Pluto is a dwarfplanet!
Earth is a Planet
Category star is Star
Finding all dwarfplanets:
Pluto

On 29 jun, 22:30, richard emberson wrote:
> The following compiles just fine:
>
>    def test(e: Planet.Value): Unit = {
>      e match {
>        case Planet.Mercury => println("Mercury")
>      }
>    }
>
> but calling
>
> test(Planet.Venus)
>
> from Main at runtime yields:
>
> scala.MatchError: Venus (of class Planet$Val)
>          at Main$.test(Enum.scala:25)
>          at Main$.main(Enum.scala:31)
>     .......
>
> I prefer to an an Enum where one gets a compile-time error
> rather than a run-time error.
> And, if one adds
>
>    case _ =>
>
> to the match statement, then when Pluto becomes a Planet again,
> the compiler will not tell you nor will you get a run-time error,
> but the code for all match-statements is still wrong.
>

richard emberson
Joined: 2010-03-22,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: java enums more compact, flexible and obvious than scal

I think it does:

object Main {
sealed abstract class Status
case object Off extends Status
case object On extends Status

def test(s: Status): Unit = s match {
case Off => println("off")
}
}

scalac Test.scala
Test.scala:18: warning: match is not exhaustive!
missing combination On

def test(s: Status): Unit = s match {
^
one warning found

With Enums based upon a sealed abstract class, an incomplete
match-statement will NOT compile.

On 06/29/2011 03:36 PM, Jan van der Vorst wrote:
> I don't think this has to do with the Enum version.
>
>
> On Jun 29, 10:30 pm, richard emberson
> wrote:
>> The following compiles just fine:
>>
>> def test(e: Planet.Value): Unit = {
>> e match {
>> case Planet.Mercury => println("Mercury")
>> }
>> }
>>
>> but calling
>>
>> test(Planet.Venus)
>>
>> from Main at runtime yields:
>>
>> scala.MatchError: Venus (of class Planet$Val)
>> at Main$.test(Enum.scala:25)
>> at Main$.main(Enum.scala:31)
>> .......
>>
>> I prefer to an an Enum where one gets a compile-time error
>> rather than a run-time error.
>> And, if one adds
>>
>> case _ =>
>>
>> to the match statement, then when Pluto becomes a Planet again,
>> the compiler will not tell you nor will you get a run-time error,
>> but the code for all match-statements is still wrong.
>>
>> On 06/29/2011 01:42 AM, sross wrote:
>>
>>
>>
>>> This may be a stupid question as I am quite new to scala, but why is
>>> everyone steering away from extending the Val class in Enumeration to
>>> add properties?
>>
>>> eg.
>>
>>> object Planet extends Enumeration {
>>> protected case class Val(name: String, val mass: Double, val
>>> radius: Double) extends super.Val(nextId, name) {
>>> def surfaceGravity: Double = Planet.G * mass / (radius * radius)
>>> def surfaceWeight(otherMass: Double): Double = otherMass *
>>> surfaceGravity
>>> }
>>> implicit def valueToPlanetVal(x: Value) = x.asInstanceOf[Val]
>>
>>> val G: Double = 6.67300E-11
>>> val Mercury = Val("Mercury", 3.303e+23, 2.4397e6)
>>> val Venus = Val("Venus", 4.869e+24, 6.0518e6)
>>> val Earth = Val("Earth", 5.976e+24, 6.37814e6)
>>> val Mars = Val("Mars", 6.421e+23, 3.3972e6)
>>> val Jupiter = Val("Jupiter", 1.9e+27, 7.1492e7)
>>> val Saturn = Val("Saturn", 5.688e+26, 6.0268e7)
>>> val Uranus = Val("Uranus", 8.686e+25, 2.5559e7)
>>> val Neptune = Val("Neptune", 1.024e+26, 2.4746e7)
>>> }
>>
>>> scala> Planet.values.filter(_.radius> 7.0e6)
>>> res16: Planet.ValueSet = Planet.ValueSet(Jupiter, Saturn, Uranus,
>>> Neptune)
>>
>>> Cheers,
>>> Sean.
>>
>>> On Jun 28, 12:41 am, richard emberson
>>> wrote:
>>>> I based the Enum class I use on the Sgine's Enum class,
>>>> http://code.google.com/p/sgine/
>>
>>>> It lets one do stuff like:
>>
>>>> sealed abstract class Status extends Status.Value
>>>> object Status extends Enum[Status] {
>>>> case object Off extends Status
>>>> case object On extends Status
>>
>>>> Status(Off, On)
>>
>>>> }
>>
>>>> sealed abstract class Planet(name: String,
>>>> val mass: Double,
>>>> val radius: Double)
>>>> extends Planet.Value(name) {
>>>> def surfaceGravity: Double = Planet.G * mass / (radius * radius)
>>>> def surfaceWeight(otherMass: Double): Double = otherMass * surfaceGravity}
>>
>>>> object Planet extends Enum[Planet] {
>>>> // universal gravitational constant(m3 kg-1 s-2)
>>>> val G: Double = 6.67300E-11
>>
>>>> object Mercury extends Planet("Mercury", 3.303e+23, 2.4397e6)
>>>> object Venus extends Planet("Venus", 4.869e+24, 6.0518e6)
>>>> object Earth extends Planet("Earth", 5.976e+24, 6.37814e6)
>>>> object Mars extends Planet("Mars", 6.421e+23, 3.3972e6)
>>>> object Jupiter extends Planet("Jupitier", 1.9e+27, 7.1492e7)
>>>> object Saturn extends Planet("Saturn", 5.688e+26, 6.0268e7)
>>>> object Uranus extends Planet("Uranus", 8.686e+25, 2.5559e7)
>>>> object Neptune extends Planet("Neptune", 1.024e+26, 2.4746e7)
>>
>>>> Planet(Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune)
>>
>>>> }
>>
>>>> Yea, you have to create a sealed class and object and you
>>>> have to register the enum members, but it gives me what I want.
>>
>>>> Also, in my modified version I do not get the "MODULE$" field
>>>> of the enum class (but, as a result, mine is not quite as a clean as
>>>> the Sgine version).
>>
>>>> Richard
>>
>>>> On 06/27/2011 04:06 PM, john sullivan wrote:
>>
>>>>> Your feedback? This is what I do now instead of Java enums. It might not
>>>>> be the best approach, but it's what I came up with.
>>
>>>>> http://scabl.blogspot.com/2011/06/scala-enums.html
>>
>>>> --
>>>> Quis custodiet ipsos custodes
>>
>> --
>> Quis custodiet ipsos custodes
>

richard emberson
Joined: 2010-03-22,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: java enums more compact, flexible and obvious than scal

I do NOT want "normal matching behavior" with Enums.

object Main {
sealed abstract class Status
case object Off extends Status
case object On extends Status

def test(s: Status): Unit = s match {
case Off => println("off")
}
}

scalac Test.scala
Test.scala:18: warning: match is not exhaustive!
missing combination On

def test(s: Status): Unit = s match {
^
one warning found

Yea, design decisions are important.
Folks are welcome to use whatever Enums they want. I
prefer my Enums to allow for strict compile-time
exhaustive pattern matching checking.

On 06/29/2011 03:43 PM, Dave wrote:
> But that is normal pattern matching behaviour. It has nothing to do
> with enumerations.
> Like this simple example, it compiles fine but in runtime it 's an
> error which it should do because 3 cannot go anywhere:
>
> package patternmatching
>
> object Main extends App {
>
> def test(n: Int) = n match {
> case 1 => println(n)
> case 2 => println(n)
> }
>
> test(1)
> test(2)
> test(3)
> }
> Output
> 1
> 2
> scala.MatchError: 3 (of class java.lang.Integer)
>
> If Pluto becomes a Planet again then you should adjust and recompile
> your enumeration again and you add also a case for Planet.Pluto in
> your main application.
>
> If you want to make the design more flexible then you should
> reconsider your design and use for instance an astronomical object
> name enumeration object with values earth, sun, mars, venus, pluto etc
> and a astronomical object type enumeration object with star, planet,
> dwarf planet, asteroid, etc as a property on that astronomical object
> name or vice versa depending on what you are doing.
>
> Another option is to store the data that might change frequently in a
> database and build a user interface to change the settings.
>
> Enumerations are good for a known set of data that are unlikely to
> change much and thus can be hard-coded in the software.
>
> A good design decision is still important with Scala, Scala doesn't
> make a poor design better.
>
> Combining the WeekDay and the Planet enumeration examples:
>
>
> package dualenums
>
> object AOCategory extends Enumeration ("Star", "Planet",
> "Dwarfplanet", "Asteroid"){
> type AOCategory = Value
> val STAR, PLANET, DWARFPLANET, ASTEROID = Value
> }
>
> object AstronomicalObject extends Enumeration {
> import AOCategory._ //importing the type AOCategory
> protected case class Val(name: String, val category: AOCategory)
> extends super.Val(nextId, name)
> implicit def valueToAstronomicalObjectVal(x: Value) =
> x.asInstanceOf[Val]
> type AstronomicalObject = Value
> val SUN = Val("Sun", STAR)
> val MERCURY = Val("Mercury", PLANET)
> val VENUS = Val("Venus", PLANET)
> val EARTH = Val("Earth", PLANET)
> val MARS = Val("Mars", PLANET)
> val JUPITER = Val("Jupiter", PLANET)
> val SATURN = Val("Saturn", PLANET)
> val URANUS = Val("Uranus", PLANET)
> val NEPTUNE = Val("Neptune", PLANET)
> val PLUTO = Val("Pluto", DWARFPLANET)
> }
>
> object Main extends App {
>
> import AstronomicalObject._ //importing the type
> AstronomicalObject
> def test(ao: AstronomicalObject) = ao.category match {
> case AOCategory.STAR => println(ao.name + "
> is a star!")
> case AOCategory.PLANET => println(ao.name +
> " is a planet!")
> case AOCategory.DWARFPLANET =>
> println(ao.name + " is a dwarfplanet!")
> case AOCategory.ASTEROID => println(ao.name
> + " is a asteroid!")
> case _ => println("Unknown object " + ao.name
> + " found!")
> }
>
> for(ao<- AstronomicalObject.values) test(ao)
> // withName is case-sensitive, typo means
> java.util.NoSuchElementException: None.get
> println("Earth is a " +
> AstronomicalObject.withName("Earth").category)
> println("Category star is " + AOCategory.withName("Star"))
> println("Finding all dwarfplanets:")
> AstronomicalObject.values.filter(_.category ==
> AOCategory.DWARFPLANET).foreach(println)
> }
>
> Output:
> Sun is a star!
> Mercury is a planet!
> Venus is a planet!
> Earth is a planet!
> Mars is a planet!
> Jupiter is a planet!
> Saturn is a planet!
> Uranus is a planet!
> Neptune is a planet!
> Pluto is a dwarfplanet!
> Earth is a Planet
> Category star is Star
> Finding all dwarfplanets:
> Pluto
>
> On 29 jun, 22:30, richard emberson wrote:
>> The following compiles just fine:
>>
>> def test(e: Planet.Value): Unit = {
>> e match {
>> case Planet.Mercury => println("Mercury")
>> }
>> }
>>
>> but calling
>>
>> test(Planet.Venus)
>>
>> from Main at runtime yields:
>>
>> scala.MatchError: Venus (of class Planet$Val)
>> at Main$.test(Enum.scala:25)
>> at Main$.main(Enum.scala:31)
>> .......
>>
>> I prefer to an an Enum where one gets a compile-time error
>> rather than a run-time error.
>> And, if one adds
>>
>> case _ =>
>>
>> to the match statement, then when Pluto becomes a Planet again,
>> the compiler will not tell you nor will you get a run-time error,
>> but the code for all match-statements is still wrong.
>>
>

DaveScala
Joined: 2011-03-18,
User offline. Last seen 1 year 21 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

C:\scala-2.9.0.1\release>scalac patternmatching.scala
patternmatching.scala:8: warning: match is not exhaustive!
missing combination On

def test(s: Status): Unit = s match {
^
one warning found

C:\scala-2.9.0.1\release>scala patternmatching.Main
off
scala.MatchError: On (of class patternmatching.Main$On$)
at patternmatching.Main$.test(patternmatching.scala:8)
at patternmatching.Main$delayedInit
$body.apply(patternmatching.scala:12)

warning: match is not exhaustive is just a warning: it still compiles
and you can run it and get the MatchError in runtime as an Int would.
It's just an extra notification, some other programmers in particular
beginners will appreciate this, there are more stakeholders who also
use the Scala API. I think this warning should be for Int pattern
matching too since it is known by the compiler what an Int is (but
then only 'warning: match is not exhaustive! missing Int combinations
or _'. Not a list of all Int combinations that are missing.)

I don't like a different behaviour for enum pattern matching, then it
should not compile for all pattern matchings for instance also for Int
pattern matching if not all possible Ints are handled and 'case _' is
missing, because otherwise pattern matching becomes inconsistent en
unintuitive and then other folks are complaining about that.

On 30 jun, 01:24, richard emberson wrote:
> I do NOT want "normal matching behavior" with Enums.
>
> object Main {
>    sealed abstract class Status
>    case object Off   extends Status
>    case object On    extends Status
>
>    def test(s: Status): Unit = s match {
>      case Off => println("off")
>    }
>
> }
>
> scalac Test.scala
> Test.scala:18: warning: match is not exhaustive!
> missing combination             On
>
>    def test(s: Status): Unit = s match {
>                                ^
> one warning found
>
> Yea, design decisions are important.
> Folks are welcome to use whatever Enums they want. I
> prefer my Enums to allow for strict compile-time
> exhaustive pattern matching checking.
>
> On 06/29/2011 03:43 PM, Dave wrote:
>
>
>
>
>
> > But that is normal pattern matching behaviour. It has nothing to do
> > with enumerations.
> > Like this simple example, it compiles fine but in runtime it 's an
> > error which it should do because 3 cannot go anywhere:
>
> > package patternmatching
>
> > object Main extends App {
>
> >      def test(n: Int) = n match {
> >                           case 1 =>   println(n)
> >                           case 2 =>   println(n)
> >                         }
>
> >      test(1)
> >      test(2)
> >      test(3)
> > }
> > Output
> > 1
> > 2
> > scala.MatchError: 3 (of class java.lang.Integer)
>
> > If Pluto becomes a Planet again then you should adjust and recompile
> > your enumeration again and you add also a case for Planet.Pluto in
> > your main application.
>
> > If you want to make the design more flexible then you should
> > reconsider your design and use for instance an astronomical object
> > name enumeration object with values earth, sun, mars, venus, pluto etc
> > and a astronomical object type enumeration object with star, planet,
> > dwarf planet, asteroid, etc as a property on that astronomical object
> > name or vice versa depending on what you are doing.
>
> > Another option is to store the data that might change frequently in a
> > database and build a user interface to change the settings.
>
> > Enumerations are good for a known set of data that are unlikely to
> > change much and thus can be hard-coded in the software.
>
> > A good design decision is still important with Scala, Scala doesn't
> > make a poor design better.
>
> > Combining the WeekDay and the Planet enumeration examples:
>
> > package dualenums
>
> > object AOCategory extends Enumeration ("Star", "Planet",
> > "Dwarfplanet", "Asteroid"){
> >         type AOCategory = Value
> >         val STAR, PLANET, DWARFPLANET, ASTEROID = Value
> > }
>
> > object AstronomicalObject extends Enumeration {
> >      import AOCategory._ //importing the type AOCategory
> >      protected case class Val(name: String, val category: AOCategory)
> > extends super.Val(nextId, name)
> >      implicit def valueToAstronomicalObjectVal(x: Value) =
> > x.asInstanceOf[Val]
> >      type AstronomicalObject = Value
> >      val SUN = Val("Sun", STAR)
> >      val MERCURY = Val("Mercury", PLANET)
> >      val VENUS = Val("Venus", PLANET)
> >      val EARTH = Val("Earth", PLANET)
> >      val MARS = Val("Mars", PLANET)
> >      val JUPITER = Val("Jupiter", PLANET)
> >      val SATURN = Val("Saturn", PLANET)
> >      val URANUS = Val("Uranus", PLANET)
> >      val NEPTUNE = Val("Neptune", PLANET)
> >      val PLUTO = Val("Pluto", DWARFPLANET)
> > }
>
> > object Main extends App {
>
> >      import AstronomicalObject._ //importing the type
> > AstronomicalObject
> >      def test(ao: AstronomicalObject) = ao.category match {
> >                           case AOCategory.STAR =>  println(ao.name + "
> > is a star!")
> >                           case AOCategory.PLANET =>   println(ao.name +
> > " is a planet!")
> >                           case AOCategory.DWARFPLANET =>
> > println(ao.name + " is a dwarfplanet!")
> >                           case AOCategory.ASTEROID =>   println(ao.name
> > + " is a asteroid!")
> >                           case _ =>  println("Unknown object " + ao.name
> > + " found!")
> >                         }
>
> >      for(ao<- AstronomicalObject.values) test(ao)
> >      // withName is case-sensitive, typo means
> > java.util.NoSuchElementException: None.get
> >      println("Earth is a " +
> > AstronomicalObject.withName("Earth").category)
> >      println("Category star is " + AOCategory.withName("Star"))
> >      println("Finding all dwarfplanets:")
> >      AstronomicalObject.values.filter(_.category ==
> > AOCategory.DWARFPLANET).foreach(println)
> > }
>
> > Output:
> > Sun is a star!
> > Mercury is a planet!
> > Venus is a planet!
> > Earth is a planet!
> > Mars is a planet!
> > Jupiter is a planet!
> > Saturn is a planet!
> > Uranus is a planet!
> > Neptune is a planet!
> > Pluto is a dwarfplanet!
> > Earth is a Planet
> > Category star is Star
> > Finding all dwarfplanets:
> > Pluto
>
> > On 29 jun, 22:30, richard emberson  wrote:
> >> The following compiles just fine:
>
> >>     def test(e: Planet.Value): Unit = {
> >>       e match {
> >>         case Planet.Mercury =>  println("Mercury")
> >>       }
> >>     }
>
> >> but calling
>
> >> test(Planet.Venus)
>
> >> from Main at runtime yields:
>
> >> scala.MatchError: Venus (of class Planet$Val)
> >>           at Main$.test(Enum.scala:25)
> >>           at Main$.main(Enum.scala:31)
> >>      .......
>
> >> I prefer to an an Enum where one gets a compile-time error
> >> rather than a run-time error.
> >> And, if one adds
>
> >>     case _ =>
>
> >> to the match statement, then when Pluto becomes a Planet again,
> >> the compiler will not tell you nor will you get a run-time error,
> >> but the code for all match-statements is still wrong.
>
> --
> Quis custodiet ipsos custodes- Tekst uit oorspronkelijk bericht niet weergeven -
>
> - Tekst uit oorspronkelijk bericht weergeven -

Tony Morris 2
Joined: 2009-03-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: java enums more compact, flexible and obvious than scal

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 30/06/11 09:24, richard emberson wrote:
> I prefer my Enums to allow for strict compile-time exhaustive
> pattern matching checking.
Scala is a non-total language. Try Agda.

joseph
Joined: 2011-06-10,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: java enums more compact, flexible and obvious than scal
hi
before going too crazy about java enums, one should remind their drawback as wells. The ones I ca quickly round up are:- they can extend anything- they don't play ball with generics - they have compilation issue when other static stuff are involved
so nothing I'm longing for... 
In the end, only their conciseness is appealing I guess... 
++

I really prefer a sealed class 
On Thu, Jun 30, 2011 at 1:17 PM, Tony Morris <tonymorris [at] gmail [dot] com> wrote:

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 30/06/11 09:24, richard emberson wrote:
> I prefer my Enums to allow for strict compile-time exhaustive
> pattern matching checking.
Scala is a non-total language. Try Agda.

- --
Tony Morris
http://tmorris.net/

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.10 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAk4MW0IACgkQmnpgrYe6r61hEwCgtPyXtqPW+rb+0D9ycWpJL0b3
Gh0AoLvHedbf6QA5V6qPkD6GLNraGmc0
=Ly1p
-----END PGP SIGNATURE-----


Stefan Langer
Joined: 2009-10-23,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: java enums more compact, flexible and obvious than scal

So what is your objection on case objects or case classes with using
traits to define common functionality vs. Java enums?

.Stefan

2011/6/30 Joseph Pachod :
> hi
> before going too crazy about java enums, one should remind their drawback as
> wells. The ones I ca quickly round up are:
> - they can extend anything
> - they don't play ball with generics
> - they have compilation issue when other static stuff are involved
> so nothing I'm longing for...
> In the end, only their conciseness is appealing I guess...
> ++
>
> I really prefer a sealed class
> On Thu, Jun 30, 2011 at 1:17 PM, Tony Morris wrote:
>>
>> -----BEGIN PGP SIGNED MESSAGE-----
>> Hash: SHA1
>>
>> On 30/06/11 09:24, richard emberson wrote:
>> > I prefer my Enums to allow for strict compile-time exhaustive
>> > pattern matching checking.
>> Scala is a non-total language. Try Agda.
>>
>> - --
>> Tony Morris
>> http://tmorris.net/
>>
>> -----BEGIN PGP SIGNATURE-----
>> Version: GnuPG v1.4.10 (GNU/Linux)
>> Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/
>>
>> iEYEARECAAYFAk4MW0IACgkQmnpgrYe6r61hEwCgtPyXtqPW+rb+0D9ycWpJL0b3
>> Gh0AoLvHedbf6QA5V6qPkD6GLNraGmc0
>> =Ly1p
>> -----END PGP SIGNATURE-----
>>
>
>

Chris Marshall
Joined: 2009-06-17,
User offline. Last seen 44 weeks 3 days ago.
RE: Re: java enums more compact, flexible and obvious than scal
val dow = DayOfWeek.withName(resultSet.getStriung("DayOfWeek"))
Oh dear.
Chris


> From: mailtolanger [at] googlemail [dot] com
> Date: Thu, 30 Jun 2011 13:46:17 +0200
> Subject: Re: [scala-user] Re: java enums more compact, flexible and obvious than scala's equivalent?
> To: scala-user [at] googlegroups [dot] com
>
> So what is your objection on case objects or case classes with using
> traits to define common functionality vs. Java enums?
>
> .Stefan
>
> 2011/6/30 Joseph Pachod <joseph [dot] pachod [at] gmail [dot] com>:
> > hi
> > before going too crazy about java enums, one should remind their drawback as
> > wells. The ones I ca quickly round up are:
> > - they can extend anything
> > - they don't play ball with generics
> > - they have compilation issue when other static stuff are involved
> > so nothing I'm longing for...
> > In the end, only their conciseness is appealing I guess...
> > ++
> >
> > I really prefer a sealed class
> > On Thu, Jun 30, 2011 at 1:17 PM, Tony Morris <tonymorris [at] gmail [dot] com> wrote:
> >>
> >> -----BEGIN PGP SIGNED MESSAGE-----
> >> Hash: SHA1
> >>
> >> On 30/06/11 09:24, richard emberson wrote:
> >> > I prefer my Enums to allow for strict compile-time exhaustive
> >> > pattern matching checking.
> >> Scala is a non-total language. Try Agda.
> >>
> >> - --
> >> Tony Morris
> >> http://tmorris.net/
> >>
> >> -----BEGIN PGP SIGNATURE-----
> >> Version: GnuPG v1.4.10 (GNU/Linux)
> >> Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/
> >>
> >> iEYEARECAAYFAk4MW0IACgkQmnpgrYe6r61hEwCgtPyXtqPW+rb+0D9ycWpJL0b3
> >> Gh0AoLvHedbf6QA5V6qPkD6GLNraGmc0
> >> =Ly1p
> >> -----END PGP SIGNATURE-----
> >>
> >
> >
Philippe Lhoste
Joined: 2010-09-02,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

On 29/06/2011 19:34, Dave wrote:
> - Pluto is not a planet

Maybe it was still a planet when the original Java example on the enums was created...

sross
Joined: 2011-06-29,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

Thanks for the feedback everyone, I've added the solution to the SO
post.

On Jun 29, 6:57 pm, Jan van der Vorst wrote:
> Well, it was an interesting exercise. I agree with all points.
>
> On Jun 29, 7:34 pm, Dave wrote:
>
>
>
>
>
>
>
> > I think Sean's solution should be the second usage example in
> > Enumeration.scala/Scaladoc.
>
> > The problem(s) I have with Jan's (last) solution is that:
> > - it is a duplicate functionality, a fork on Enumeration and then
> > modified the Enumeration class (duplicate code is hard too maintain,
> > avoid duplicate code what's already in the API as much as possible).
> > - MyEnumeration is not extending standard Scala Enumeration  (where is
> > withName?) so it is not compatible with existing Enumeration
> > If someone made a framework/library that uses Enumeration, you'll have
> > to change that framework as well in order to use it (poor reusibility)
> > - it's an object and a class solution, not one object solution and the
> > total solution is bigger
> > - Pluto is not a planet

Jan van der Vorst
Joined: 2011-06-02,
User offline. Last seen 42 years 45 weeks ago.
Re: java enums more compact, flexible and obvious than scala's e

Sean, excelent!
I just saw that one could make it even a little bit more concise by
leaving out the name and nextId params.
That way you can leave out the names in the Val too.

object Planet extends Enumeration {
protected case class Val(val mass: Double, val radius: Double)
extends super.Val {
def surfaceGravity: Double = Planet.G * mass / (radius * radius)
def surfaceWeight(otherMass: Double): Double = otherMass *
surfaceGravity
}

implicit def valueToPlanetVal(x: Value) = x.asInstanceOf[Val]

val G: Double = 6.67300E-11
val Mercury = Val(3.303e+23, 2.4397e6)
val Venus = Val(4.869e+24, 6.0518e6)
val Earth = Val(5.976e+24, 6.37814e6)
val Mars = Val(6.421e+23, 3.3972e6)
val Jupiter = Val(1.9e+27, 7.1492e7)
val Saturn = Val(5.688e+26, 6.0268e7)
val Uranus = Val(8.686e+25, 2.5559e7)
val Neptune = Val(1.024e+26, 2.4746e7)

}

On Jul 1, 12:03 pm, sross wrote:
> Thanks for the feedback everyone, I've added the solution to the SO
> post.
>
> On Jun 29, 6:57 pm, Jan van der Vorst wrote:
>
>
>
> > Well, it was an interesting exercise. I agree with all points.
>
> > On Jun 29, 7:34 pm, Dave wrote:
>
> > > I think Sean's solution should be the second usage example in
> > > Enumeration.scala/Scaladoc.
>
> > > The problem(s) I have with Jan's (last) solution is that:
> > > - it is a duplicate functionality, a fork on Enumeration and then
> > > modified the Enumeration class (duplicate code is hard too maintain,
> > > avoid duplicate code what's already in the API as much as possible).
> > > - MyEnumeration is not extending standard Scala Enumeration  (where is
> > > withName?) so it is not compatible with existing Enumeration
> > > If someone made a framework/library that uses Enumeration, you'll have
> > > to change that framework as well in order to use it (poor reusibility)
> > > - it's an object and a class solution, not one object solution and the
> > > total solution is bigger
> > > - Pluto is not a planet- Hide quoted text -
>
> - Show quoted text -

Jim Powers
Joined: 2011-01-24,
User offline. Last seen 36 weeks 2 days ago.
Re: java enums more compact, flexible and obvious than scala's
On Tue, Jun 28, 2011 at 3:20 PM, Ken McDonald <ykkenmcd [at] gmail [dot] com> wrote:
As mentioned before, I'm certainly willing to have a go at learning category theory if someone can point me at a link (Category Theory For The Compleat Idiot would be good.) This page is getting so crowded, might be best to email me as well as posting: ykkenmcd _ at _ gmail.com.

I recently got pointed to this book: http://www.amazon.com/gp/product/0199237182
Category TheoryBy: Steve Awodey

I just received it today.  A quick perusal seems to support the claim that it's relatively approachable for the non-professional mathematician.  The person who recommended it was very enthusiastic about it.  Hope that helps.
--
Jim Powers

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