https://kotlinlang.org logo
#kotest
Title
# kotest
r

Rob Elliot

03/24/2022, 10:44 AM
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

christophsturm

03/24/2022, 10:51 AM
why not
val x: ExpectedType = expression
? that will fail at compile time
r

Rob Elliot

03/24/2022, 10:53 AM
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>()
2 Views