|
| 1 | +import reflect.ClassTag |
| 2 | + |
| 3 | +/** Some delayed computation like a Mill Task */ |
| 4 | +case class Task[T](body: () => T) |
| 5 | + |
| 6 | +object SeqLits: |
| 7 | + |
| 8 | + /** A typeclass to map sequence literals with `T` elements |
| 9 | + * to some collection type `C`. |
| 10 | + */ |
| 11 | + trait FromArray[T, +C]: |
| 12 | + inline def fromArray(inline xs: IArray[T]): C |
| 13 | + |
| 14 | + /** An emulation of a sequence literal like [1, 2, 3]. Since we don't have that |
| 15 | + * syntax yet, we express it here as `seqLit(1, 2, 3)`. |
| 16 | + */ |
| 17 | + inline def seqLit[T: ClassTag, C](inline xs: T*)(using inline f: FromArray[T, C]): C = |
| 18 | + f.fromArray(IArray(xs*)) |
| 19 | + |
| 20 | + /** Straightfoward mapping to Seq */ |
| 21 | + given [T] => FromArray[T, Seq[T]]: |
| 22 | + inline def fromArray(inline xs: IArray[T]) = Seq(xs*) |
| 23 | + |
| 24 | + /** A more specific mapping to Vector */ |
| 25 | + given [T] => FromArray[T, Vector[T]]: |
| 26 | + inline def fromArray(inline xs: IArray[T]) = Vector(xs*) |
| 27 | + |
| 28 | + /** A delaying mapping to Task */ |
| 29 | + given [T] => FromArray[T, Task[Seq[T]]]: |
| 30 | + inline def fromArray(inline xs: IArray[T]) = Task(() => Seq(xs*)) |
| 31 | + |
| 32 | + def last: Int = { println("last was evaluated"); 4 } |
| 33 | + |
| 34 | + val s: Seq[Int] = seqLit(1, 2, 3, last) |
| 35 | + val v: Vector[Int] = seqLit(1, 2, 3, last) |
| 36 | + val t: Task[Seq[Int]] = seqLit(1, 2, 3, last) |
| 37 | + |
| 38 | + @main def Test = |
| 39 | + println(s"Seq $s") |
| 40 | + println(s"Vector $v") |
| 41 | + println(s"${t.getClass.getSimpleName} with elems ${t.body()}") |
0 commit comments