Difference between `*` and `Any` in Kotlin generics: star vs Any
Hi everyone! I recently started learning Kotlin and encountered an unclear point in generics. \n\nIn the documentation, I saw that you can use `*` (star projection) in generics, and you can also write ``. At first glance, it seems they do the same thing — allow storing any types in a collection. But I feel there is some important difference between them.\n\nFor example, I write this code:\n\n```kotlin\nval list1: MutableList = mutableListOf("string", 42, 3.14)\nval list2: MutableList<*> = mutableListOf("string", 42, 3.14)\n```\n\nBoth variables work, and I can add any element to them. But if I try to read an element and assign it to a variable with a specific type, strange things happen.\n\nIf I write:\n```kotlin\nval item1: String = list1[0] // Compilation error?
No answers yet.
Log in to leave an answer