In these cases, the Scala value class will be “boxed”, right?

后端 未结 3 653
-上瘾入骨i
-上瘾入骨i 2021-01-02 13:51

If I have this value class:

class ActionId(val value: Int) extends AnyVal

Then, in all the examples below, an object will be allocated for

3条回答
  •  耶瑟儿~
    2021-01-02 14:28

    With some implicit casts it is actually possible to get around the array-issue without the syntactic required by rex-kerr. I used it in conjunction with How to reduce the number of objects created in Scala?

    Y.scala:

    import scala.language.implicitConversions
    
    class Y(val repr: String) extends AnyVal {}
    object Y {
        implicit def stringToY (v:String) = new Y(v)
        implicit def yToString (v:Y) = v.repr
    }
    

    Main file:

    import Y._
    
    val y1 = new Y("apple")    // unboxed
    val y2 = new Y("orange")   // unboxed
    val ys: Array[String] = Array(y1, y2)   // Implicit cast
    val y3:Y = ys(0)
    

提交回复
热议问题