Is there a way how to prevent/forbid upcasting? In...
# getting-started
d
Is there a way how to prevent/forbid upcasting? In my test lib I have this method:
Copy code
fun <T> assertEqualsRecursive(actual: T, expected: T, vararg ignoringFields: String) {
I would like to ensure that the objects passed are exactly of the same type, so that the compiler doesn't attempt any silent upcasting.
c
There is no officially supported way. Workaround 1: use the internal annotation
OnlyInputTypes
:
Copy code
fun <@OnlyInputTypes T> assertEqualsRecursive(actual: T, expected: T, vararg ignoringFields: String) {
Since it's internal, there's a bit of setup required to use it. Workaround 2: split your usage into two different functions. For example,
Copy code
assertThat(actual)
    .equalsRecursive(expected, "foo", "bar")
This way, the type is bound on the first function call. No upcasting can happen on the second function call.
👍 2
d
Thanks. I guess in my specific situation workaround 2 could be actually considered the proper solution 🙂