https://kotlinlang.org logo
Title
m

Miguel Vargas

12/17/2021, 10:33 PM
Trying to come up with a test function to assert that every member of a list is of a specified type. This what I’ve tried
fun assertListTypes(list: List<ParentType>, types: List<KType>) {
    assertEquals(list.size, types.size)
    types.forEachIndexed { idx, type ->
        assert(list[idx] is type)
    }
}

assertListTypes(list, listOf(typeOf<Class1>(), typeOf<Class2>()))
But the compiler didn’t like the
is
check on the KType. Any ideas?
m

mkrussel

12/17/2021, 10:36 PM
is
checks can only be done with compile time constants on the right hand side. Instead you have to use reflection functions to determine if it is that type.
KClass.isInstance
could do that but I don't see anything on
KType
.
m

Miguel Vargas

12/17/2021, 10:40 PM
thanks, let me try with KClass
that worked!
like this
fun assertListTypes(list: List<ParentType>, types: List<KClass<*>>) {
    assertEquals(list.size, types.size)
    types.forEachIndexed { idx, type ->
        assert(type.isInstance(list[idx]))
    }
}
    
assertListTypes(list, listOf(Class1::class, Class2::class))
thanks for the help!
d

Daniel

12/19/2021, 2:36 PM
The requirement seems fishy. What would speak against equals asserting against a expected list?