我正在学习Scala,我无法弄清楚如何在Scala中最好地表达这个简单的Java类:
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
}
我所拥有的最好成绩如下:
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)
但是我失去了将BLACK,WHITE和GREEN与Color命名空间联系起来的优势。
答案 0 :(得分:17)
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)
}
答案 1 :(得分:13)
您可以将特定颜色放入伴侣对象中:
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)
}
修改强>:
或者,您可以在随播对象中包含val:
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)
}
你可以让他们懒得延迟实例化直到使用它们:
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)
}
回到原始解决方案,你可以阻止类的扩展(通过使Color类密封来模拟“final”:
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)
}
答案 2 :(得分:1)
sealed允许对象扩展具有相同的物理文件。不在不同的文件中。密封比最终包装范围更接近。