Equivalent of open static trailing fields in Scala

I am learning Scala and I cannot 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'm losing the benefits of having BLACK, WHITE, and GREEN bound to the Color namespace.

+7
java scala
source share
3 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) } 
+17
source share

You can simply put certain colors in a companion object:

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

EDIT

Alternatively, you can have vals inside the companion object:

 class Color(val red: Int, val blue: Int, val green: Int) object Color { val BLACK = new Color(0, 0, 0) val WHITE = new Color(255, 255, 255) val GREEN = new Color(0, 0, 255) } 

You can make them lazy to defer instantiation until they are used:

 class Color(val red: Int, val blue: Int, val green: Int) object Color { lazy val BLACK = new Color(0, 0, 0) lazy val WHITE = new Color(255, 255, 255) lazy val GREEN = new Color(0, 0, 255) } 

By returning the original solution, you can prevent the class from expanding (by simulating "final" by making the Color class leakproof:

 sealed class Color(val red: Int, val blue: Int, val green: Int) object Color { object BLACK extends Color(0, 0, 0) object WHITE extends Color(255, 255, 255) object GREEN extends Color(0, 0, 255) } 
+13
source share

Sealed allows you to expand objects with the same physical file ... not in another file. sealed closer to bag size than final.

+1
source share

All Articles