Skip to content

Commit 3fb949c

Browse files
committed
A strawman for aggregate literals
A test case that shows that we can have an "inline type class" that allows to use a typeclass-based scheme for sequence literals where instances can be created with macros.
1 parent 58f88a6 commit 3fb949c

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

tests/pos/seqlits.check

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
last was evaluated
2+
last was evaluated
3+
Seq List(1, 2, 3, 4)
4+
Vector Vector(1, 2, 3, 4)
5+
last was evaluated
6+
Task with elems List(1, 2, 3, 4)

tests/pos/seqlits.scala

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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

Comments
 (0)