For a DSL, I want to introduce a dup
extension method that basically calls Vector.fill
, e.g.
import scala.collection.immutable.{IndexedSeq => Vec}
implicit final class Dup[A](private val in: A) extends AnyVal {
def dup(n: Int): Vec[A] = Vector.fill(n)(in)
}
3 dup 4 // Vector(3, 3, 3, 3)
Now I want to make the argument a by-name value, so that the following would work correctly:
math.random dup 4 // wrong: four times the same value
I am looking at this question, so apparently there is no solution with a plain value class, only:
final class Dup[A](in: () => A) {
def dup(n: Int): Vec[A] = Vector.fill(n)(in())
}
implicit def Dup[A](in: => A): Dup[A] = new Dup(() => in)
math.random dup 4 // ok
...undoing the advantage of a value-class that there is no boxing involved.
So I was wondering, would it be possible to write a macro that provides a no-instantiation solution where the argument is by-name?