How does the reified keyword work in Kotlin and why is it needed?
Hello everyone! I'm learning Kotlin and ran into a problem working with generics. I'm trying to write a simple function that takes a list and returns the number of elements of a specific type. For example, I want to count how many strings or numbers are in the list. Here's my code:
```kotlin
fun countElements(list: List): Int {
return list.filter { it is T }.count() // Error: Cannot check for instance of erased type: T
}
```
The compiler complains and says that you cannot check type T at runtime. I've read about type erasure in Java, but I thought Kotlin had solved this somehow. Then I found the `reified` keyword, but I don't fully understand how to use it and what it actually does.
Can you explain with examples:
1. Why does this error occur?
No answers yet.
Log in to leave an answer