The Artima Developer Community
Sponsored Link

Programming in Scala Forum
indexed view on case classes

1 reply on 1 page. Most recent reply: Feb 6, 2008 6:05 AM by Javier Diaz Soto

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Jan Van Besien

Posts: 8
Nickname: jvb
Registered: Feb, 2008

indexed view on case classes Posted: Feb 1, 2008 4:33 AM
Reply to this message Reply
Advertisement
Hi all

I have 8 case classes like this:

abstract class Direction

case class North extends Direction
case class NorthEast extends Direction
case class East extends Direction
case class SouthEast extends Direction
case class South extends Direction
case class SouthWest extends Direction
case class West extends Direction
case class NorthWest extends Direction

Somewhere else I want to randomly pick one of these case classes. I currently implemented it like this:

private def randomDirection:Direction = random.nextInt(8) match {
case 0 => North
case 1 => NorthEast
case 2 => East
case 3 => SouthEast
case 4 => South
case 5 => SouthWest
case 6 => West
case 7 => NorthWest
}

This doesn't look like I've found the best possible solution... Is there a way to index all the case class subclasses of my abstract Direction class or something like that? Should I maybe look into enumerations to achieve this?

thnx in advance


Javier Diaz Soto

Posts: 29
Nickname: javierbds
Registered: Sep, 2005

Re: indexed view on case classes Posted: Feb 6, 2008 6:05 AM
Reply to this message Reply
I guess you want en enum(eration):

See http://www.nabble.com/scala-enums-tt9854598.html#a9854598

sealed object Compass extends Enumeration {

val N = Value("North")
val NE= Value("NorthEast")
val E= Value("East")
val SE= Value("SouthEast")
//..
}

val r = new Random()

def randomDirection: Compass.Value = Compass(r.nextInt(Compass.maxId))

Flat View: This topic has 1 reply on 1 page
Topic: Array Zip sec 9.10 Previous Topic   Next Topic Topic: subclasses of case classes?

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use