Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of public static final fields in Scala

Tags:

java

scala

I'm learning Scala, and I can't figure out how to best express this simple Java class in Scala:

public class Color {
  public static final Color BLACK = new Color(0, 0, 0);
  public static final Color WHITE = new Color(255, 255, 255);     
  public static final Color GREEN = new Color(0, 0, 255);

  private final int red;
  private final int blue;
  private final int green;

  public Color(int red, int blue, int green) {
    this.red = red;
    this.blue = blue;
    this.green = green;
  }

  // getters, et cetera
}

The best I have is the following:

class Color(val red: Int, val blue: Int, val green: Int)
object BLACK extends Color(0, 0, 0)
object WHITE extends Color(255, 255, 255)
object GREEN extends Color(0, 0, 255)  

But I lose the advantages of having BLACK, WHITE, and GREEN being tied to the Color namespace.

like image 491
JT. Avatar asked Mar 29 '10 03:03

JT.


1 Answers

case class Color(red: Int, blue: Int, green: Int)

object Color {
  val BLACK = Color(0, 0, 0)
  val WHITE = Color(255, 255, 255)
  val GREEN = Color(0, 0, 255)
}
like image 137
missingfaktor Avatar answered Dec 01 '22 22:12

missingfaktor