Use case: I'm writing tests for a Scala 3 program using scalatest
. I want to print a meaningful fail
message saying that the expected parameterized type did not equal the found parameterized type.
eg:
Expected: scala.util.Failure[ IllegalArgumentException ]
Found: scala.util.Failure[ NotImplementedException ]
In Scala 2.13, I would use sbt to add a library dependency on "org.scala-lang" % "scala-reflect" % scalaVersion.value
, which would allow me to import the package scala.reflect.runtime.universe
and do something like this:
import org.scalatest.funspec.AnyFunSpec
import scala.reflect.runtime.universe
import scala.util.Failure
class ExampleSpec extends AnyFunSpec {
def getTypeTag[ T : universe.TypeTag ]( obj : T ) = universe.typeTag[ T ]
describe( "rejectEmptyStrings( textInput : String ) : Try[ Any ]" ) {
it( "Rejects empty strings." ) {
rejectEmptyStrings( "" ) match {
case Failure( _ : IllegalArgumentException ) => succeed
case other => fail(
"Expected: scala.util.Failure[ IllegalArgumentException ]\n" +
s"Found: ${ getTypeTag( other ).tpe }"
)
}
}
}
}
(The getTypeTag
function is provided by this page of the docs.)
But how would I do the same thing in Scala 3?
There does not seem to be a scala-reflect
package for Scala 3. Can I use the Scala 2.13 version with a cross-version dependency?
libraryDependencies += ( "org.scala-lang" % "scala-reflect" % scalaVersion.value )
.cross( CrossVersion.for3Use2_13 )
At time of writing, all of the current docs about reflection focus on metaprogramming and macros. (Not my use case.) They make no reference to TypeTags and how to access them.
And, of course, if there is a simpler solution to my use case that I'm not seeing - one that does not rely on reflection - I am open to it.