I’d like to catch, at compile time, that the return type is not String as it should be. I’ve been able to do it like this:
var v = f(); v = v : String // fails at compile time
but I was hoping for something cleaner. I tried to define a function hasType[A] so I could write:
hasType[String](f())
or even:
val v = f()
hasType[String](v)
to trigger a compile-time failure, but without success (after playing around with =:= and <:<).
(If you’re wondering about the context, I use assertCompiles and assertTypeError to check that students have written the desired Scala signatures, but I don’t want them to circumvent an exercise on polymorphism by using silly signatures like String & Option[String].)
I was close! I got the generic lambda, but I got stuck on how to incorporate the implicit evidence in it. I keep forgetting about these context functions.
I also tried this:
def hasType[U] =
def e[S](x: S)(using ev: U =:= S) = ev
e
which cannot be compiled.
Thanks a lot!
(P.S. What is the return type of your hasType, if I wanted to write it explicitly?)
Turns out that this already exists as an experimental feature, but like I suspected it doesn’t allow “unseparated” parameter lists for some reason. So you have to uglify it a little bit:
import scala.language.experimental.clauseInterleaving
def hasType[A](using DummyImplicit)[B](b: B)(using B =:= A) = b