Skip to content

Commit ce684de

Browse files
Merge pull request #11206 from Jasper-M/patch-1
add support for ToExpr[Class[?]]
2 parents 3568ecd + ab22081 commit ce684de

File tree

4 files changed

+37
-3
lines changed

4 files changed

+37
-3
lines changed

library/src/scala/quoted/ToExpr.scala

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,10 @@ object ToExpr {
8181
}
8282

8383
/** Default implemetation of `ToExpr[Class[T]]` */
84-
given ClassToExpr[T]: ToExpr[Class[T]] with {
85-
def apply(x: Class[T])(using Quotes) = {
84+
given ClassToExpr[T <: Class[?]]: ToExpr[T] with {
85+
def apply(x: T)(using Quotes) = {
8686
import quotes.reflect._
87-
Ref(defn.Predef_classOf).appliedToType(TypeRepr.typeConstructorOf(x)).asExpr.asInstanceOf[Expr[Class[T]]]
87+
Ref(defn.Predef_classOf).appliedToType(TypeRepr.typeConstructorOf(x)).asExpr.asInstanceOf[Expr[T]]
8888
}
8989
}
9090

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
long
2+
int
3+
int
4+
int
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import scala.quoted._
2+
3+
inline def wildcard: Map[String, Class[?]] = ${ wildcardMacro }
4+
inline def noWildcard: Map[String, Class[Int]] = ${ noWildcardMacro }
5+
6+
def wildcardMacro(using Quotes): Expr[Map[String, Class[?]]] = {
7+
val result: Map[String, Class[?]] = Map(
8+
"foo" -> classOf[Long],
9+
"bar" -> classOf[Int]
10+
)
11+
Expr(result)
12+
}
13+
14+
def noWildcardMacro(using Quotes): Expr[Map[String, Class[Int]]] = {
15+
val result: Map[String, Class[Int]] = Map(
16+
"foo" -> classOf[Int],
17+
"bar" -> classOf[Int]
18+
)
19+
Expr(result)
20+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
object Test {
2+
def main(args: Array[String]): Unit = {
3+
val a: Map[String, Class[?]] = wildcard
4+
val b: Map[String, Class[Int]] = noWildcard
5+
println(a("foo"))
6+
println(a("bar"))
7+
println(b("foo"))
8+
println(b("bar"))
9+
}
10+
}

0 commit comments

Comments
 (0)