zygfryd / scala-zygf-ctor   0.1.1

Creative Commons Zero v1.0 Universal GitHub

A tiny macro library for Scala that lets your generic code gain access to constructors.

Scala versions: 2.13 2.12 2.11

zygf.ctor

This is a tiny macro library for Scala that lets your generic code gain access to constructors for your type arguments.

Supported Scala versions: 2.11, 2.12, 2.13.

Usage

Artifact
"net.zygfryd" %% "ctor" % "0.1.1"
Import
import zygf.ctor.Ctor

Obtaining a function that calls the constructor matching the given signature. You can access the function via the member make of the returned object.

def foo[T](implicit ctor: Ctor[String => T]) = ctor.make("foo")

A companion object’s apply method qualifies as a constructor too:

trait Foo

object Foo {
  def apply(s: String) = ???
}

val ctor = Ctor.get[String => Foo]

Multiple parameter lists are supported as curried functions:

class Foo(val i: Int)(val s: String)

val ctor = Ctor.get[Int => String => Foo]

ctor.make(42)("foo")
Note
Implicit parameter lists need to be converted to regular parameter lists, as there’s no other way to represent them in a function signature.
class Foo(val i: Int)(implicit val s: String)

Ctor.get[Int => String => Foo] // works
Ctor.get[Int => Foo] // doesn't work

If you omitted the implicit parameter list, the compiler would look for implicit parameters at the constructor function’s creation site and not the call site.

class Foo(val i: Int)(implicit val s: String)

val ctor = {
  implicit val s: String = "foo"
  Ctor.get[Int => Foo] // works
}

{
  implicit val s: String = "bar" // ignored
  ctor.make(42) == Foo(42)("foo")
}