-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refs #10: Add NewTypeArray, support Array coercion
- Loading branch information
1 parent
7fde63c
commit e9830f5
Showing
3 changed files
with
276 additions
and
26 deletions.
There are no files selected for viewing
34 changes: 34 additions & 0 deletions
34
shared/src/main/scala/io/estatico/newtype/NewTypeArray.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package io.estatico.newtype | ||
|
||
import scala.reflect.ClassTag | ||
|
||
/** Type class for building arrays for newtypes. */ | ||
trait NewTypeArray[N] { | ||
type Repr | ||
def clsTag: ClassTag[Repr] | ||
|
||
final def empty: Array[N] = Array.empty(clsTag).asInstanceOf[Array[N]] | ||
|
||
final def apply(xs: N*): Array[N] = | ||
Array(xs.asInstanceOf[Seq[Repr]]: _*)(clsTag).asInstanceOf[Array[N]] | ||
|
||
final def upcast(a: Array[Repr]): Array[N] = a.asInstanceOf[Array[N]] | ||
|
||
final def downcast(a: Array[N]): Array[Repr] = a.asInstanceOf[Array[Repr]] | ||
} | ||
|
||
object NewTypeArray { | ||
|
||
type Aux[N, R] = NewTypeArray[N] { type Repr = R } | ||
|
||
def apply[N](implicit ev: NewTypeArray[N]): Aux[N, ev.Repr] = ev | ||
|
||
def apply[N](xs: N*)(implicit ev: NewTypeArray[N]): Array[N] = ev(xs: _*) | ||
|
||
def empty[N](implicit ev: NewTypeArray[N]): Array[N] = ev.empty | ||
|
||
def unsafeDerive[N, R](implicit ct: ClassTag[R]): Aux[N, R] = new NewTypeArray[N] { | ||
type Repr = R | ||
override def clsTag: ClassTag[Repr] = ct | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters