How to reduce the number of objects created in Scala?

后端 未结 5 1646
余生分开走
余生分开走 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:00

    You could have an interface that returns a simple Int. Then you could use implicit conversions to treat an Int as an RGB object where needed.

    case class RBGInt(red: Int, green: Int, blue: Int) {
       // ...
    }
    
    object Conversions { 
    
      implicit def toRGBInt(p: Int) = {
        val (r, g, b) = /* some bitmanipulation to turn p into 3 ints */
        RGBInt(r, g, b)
      }
    
    }
    

    Then you could treat any Int as an RGBInt where you think it makes sense:

    type RGB = Int // useful in documenting interfaces that consume
                   // or returns Ints which represent RGBs
    
    def getPixelRGB(img: Image, x: Int, y: Int): RGB = {
      // returns an Int
    }
    
    def someMethod(..) = {
      import Conversions._
      val px: RGB = getPixelRGB(...) // px is actually an Int
      px.red // px, an Int is lifted to an RGBInt
    }
    

提交回复
热议问题