How to reduce the number of objects created in Scala?

后端 未结 5 1618
余生分开走
余生分开走 2021-02-08 03:24

I\'m programming a computer graphics application in Scala which uses a RGB class to return the color at a point in the image. As you can imagine, the function which return the c

5条回答
  •  有刺的猬
    2021-02-08 04:04

    You can encode RGB with single long or int. Moreover, in scala 2.10 you can define value class for primitive values, say

    class RGB private(val underlying: Long) extends AnyVal {
      def toTriple = /*decoding to (red, green, blue)*/
    } 
    object RGB {
      def apply(red: Int, green: Int, blue: Int) = /* encode and create class with new RGB(longvalue)*/
    }
    

    With value class you can still have type information and enjoy class-less memory layout in JVM.

提交回复
热议问题