Is there a way to assert the compile time type of ...
# kotest
r
Is there a way to assert the compile time type of an expression? (I don't want a test that passes because the runtime type of the result of the expression is a subtype of the requested type - I want to assert exactly what type the compiler decided the expression had. When doing overloading with subtypes and overriding with more specific return types it's important.)
c
why not
val x: ExpectedType = expression
? that will fail at compile time
r
If
expression
returns a subtype of
ExpectedType
that will pass. So in order to prove the compile time return type is
ExpectedType
, not a subtype of
ExpectedType
, I need to use
shouldNotCompile
with every single subtype of
ExpectedType
. Which is a bit of a pain.
I'm experimenting with
io.kotest.matchers.reflection.shouldHaveReturnType
- might give me what I need.
Yup, that works. Needs kotlin-reflect on the classpath, but then you can do:
Copy code
import io.kotest.matchers.reflection.shouldHaveReturnType
import kotlin.reflect.jvm.reflect

{ expression }.reflect().shouldNotBeNull().shouldHaveReturnType<ExpectedType>()