Last active
May 30, 2021 12:07
-
-
Save xuwei-k/cd2c3c61425fdbe5a821c5859d79f328 to your computer and use it in GitHub Desktop.
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
scalaVersion := "3.0.0" |
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
package example | |
import scala.quoted.* | |
trait Close[A] { | |
def close(a: A): Unit | |
} | |
object Close { | |
implicit inline def instance[A]: Close[A] = | |
${ impl[A] } | |
def impl[A: Type](using Quotes): Expr[Close[A]] = { | |
import quotes.reflect.* | |
val method = TypeRepr.of[A].typeSymbol.declaredMethods.filter(_.name == "close") match { | |
case List(m) => | |
m | |
case Nil => | |
report.throwError("not found `close` method") | |
case values => | |
report.throwError("found multiple `close` method") | |
} | |
'{ | |
new Close[A] { | |
override def close(a: A): Unit = { | |
${Apply(Select(('a).asTerm, method), Nil).asExpr} | |
} | |
} | |
} | |
} | |
} |
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
package example | |
import scala.compiletime.testing.typeCheckErrors | |
import scala.compiletime.testing.ErrorKind | |
object Test { | |
def main(args: Array[String]): Unit = { | |
summon[Close[A1]].close(new A1()) | |
summon[Close[scala.io.Source]] | |
summon[Close[java.io.InputStream]] | |
val List(error1) = typeCheckErrors("summon[Close[A2]]") | |
assert(error1.message == "not found `close` method") | |
assert(error1.lineContent == "summon[Close[A2]]") | |
assert(error1.kind == ErrorKind.Typer) | |
val List(error2) = typeCheckErrors("summon[Close[A3]]") | |
assert(error2.message == "found multiple `close` method") | |
assert(error2.lineContent == "summon[Close[A3]]") | |
assert(error2.kind == ErrorKind.Typer) | |
} | |
} |
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
package example | |
class A1 { | |
def close(): Unit = println("close") | |
} | |
class A2 | |
trait A3 { | |
def close(): Unit | |
def close(a: Int): Unit | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment