estatico / scala-newtype

NewTypes for Scala with no runtime overhead
Apache License 2.0
540 stars 31 forks source link

@newsubtype instances cannot be used in Arrays #35

Open velvia opened 6 years ago

velvia commented 6 years ago

version 0.4.2.

object Test {
  @newsubtype case class VectorPointer(addr: Long)
 }

scala> new Array[Test.VectorPointer](10)
<console>:12: error: cannot find class tag for element type Test.VectorPointer
       new Array[Test.VectorPointer](10)
carymrobbins commented 6 years ago

I actually have a wip branch (10-as-array) which improves Array support for newtypes. At this point though, you should be fine to cast so long as you know that the types are correct. So the following may be a workaround for you -

Array[Long](10).asInstanceOf[Array[VectorPointer]]

You could wrap this into a method to improve safety -

@newsubtype case class VectorPointer(addr: Long)
object VectorPointer {
  def wrapArray(a: Array[Long]): Array[VectorPointer] = a.asInstanceOf[Array[VectorPointer]]
  def unwrapArray(a: Array[VectorPointer]): Array[Long] = a.asInstanceOf[Array[Long]]
}

scala> VectorPointer.wrapArray(Array(10))
res0: Array[VectorPointer] = Array(10)