https://kotlinlang.org logo
#getting-started
Title
# getting-started
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
Copy code
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
Copy code
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?
3 Views