So, I'm using the Scala reflections library, and I'm trying to check if a method conforms to a given type. To simplify, I'm trying to check only its output.
What I have now is:
val returnType = methodSymbol.returnType
// returnType: reflect.runtime.universe.Type = java.lang.String
So, I can read it is a String, but it has this terrible type reflect.runtime.universe.Type
. How on Earth can I compare check if this return type is a simple String? I even tried using TypeTags, which are simple enough, but to convert a Type
to a TypeTag
is such a monumental effort that I fail to believe such a simple task cannot be achieved with more simply.
So, how can I compare this to a String and simply get a boolean back?
I thought of simply calling a toString()
and trying to parse that back to a normal type, but that would be really disgusting to do on the code, IMO. Also, I cannot simply specify the method name, because I'm working on a list of methods, and more will come later.
I've seen some questions, and even this (in my opinion, absurdly complex) answer on how to convert a Type to a TypeTag, but, again, I'm baffled by the level of complexity for such a trivial task. I'm already thinking of pulling my scarce hair out. Help appreciated.
EDIT: I've managed to make the comparison for the String itself, but not for a method returning the String.
To compare the String return type, I'm doing:
val returnType = methodSymbol.returnType
returnType =:= typeTag[String].tpe
When I try to check it with inheritance and a method, though, using <:<
, it won't work. To clarify, B extends Trait A, the type signature is () => B
, but I cannot match when coding
val typeSig = methodSymbol.typeSig
typeSig <:< typeTag[() => A].tpe
returnType == typeOf[String]
?returnType
is not a TypeTag, as stated previously.typeOf
returns aType
, not aTypeTag
, as far as I know. See this Scastie playground: scastie.scala-lang.org/sQDO2hDJThyKuUiWaZWRmQ