-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Generating a match case with wildcard types #19325
-
Hello,
given a TypeRepr
which represents an applied generic type such as List[String]
, I'd like to generate a match case:
case List[_] =>
(to avoid unchecked warnings). I've got this working for non-generic types, but the wildcards pose a problem. Here's what I got so far:
myTypeRepr.classSymbol match case Some(sym) if myTypeRepr.typeArgs.nonEmpty => // is generic val wildcardTypeParameters: List[Tree] = List.fill(orType.typeArgs.length)(WildcardTypeTree(TypeBounds(TypeRepr.of[Any], TypeRepr.of[Nothing]))) Some(CaseDef(Typed(Wildcard(), Applied(TypeIdent(sym), wildcardTypeParameters)), None, caseThen)) // other cases
However, this leads to a compile-time error:
[error] |Term-dependent types are experimental,
[error] |they must be enabled with a `experimental.dependent` language import or setting
In other cases I'm using Typed(Wildcard(), TypeIdent(sym))
, so I suspect this must be something with wildcardTypeParameters
, but I'm a bit stuck trying to find exactly what.
Or maybe I'm trying to approach this wrong the wrong angle?
Thanks :)
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 2 comments 2 replies
-
I'm pretty sure the lower bound comes first and the higher bound comes second:
TypeBounds(TypeRepr.of[Nothing], TypeRepr.of[Any])
Beta Was this translation helpful? Give feedback.
All reactions
-
Ah yes, thanks :) Of course I swapped these ... still, getting the same error during compilation
Beta Was this translation helpful? Give feedback.
All reactions
-
I remembered correctly that the order in the trailer company is hi-lo.
Ah yes, see the "then" photo, that's what it looked like in childhood.
Beta Was this translation helpful? Give feedback.
All reactions
-
Not sure what was wrong with the original one, but this one works:
myTypeRepr.classSymbol match case Some(sym) if myTypeRepr.typeArgs.nonEmpty => // is generic val wildcardTypeParameters: List[Tree] = List.fill(orType.typeArgs.length)(TypeBoundsTree(TypeTree.of[Nothing], TypeTree.of[Any])) Some(CaseDef(Typed(Wildcard(), Applied(TypeIdent(sym), wildcardTypeParameters)), None, caseThen))
this variant is based on the output of printing the tree for Nil match { case _: List[_ >: Nothing <: Any] => }
, which is reported as:
Inlined(None, Nil, Block(Nil, Match(Ident("Nil"), List(CaseDef(Typed(Wildcard(), Applied(TypeIdent("List"), List(TypeBind(_$1, TypeBoundsTree(TypeIdent("Nothing"), TypeIdent("Any")))))), None, Block(Nil, Literal(UnitConstant())))))))
I don't have the TypeBind(...)
wrapper, but it seems it's not necessary.
Beta Was this translation helpful? Give feedback.