Why can't we just do: ```class LootBox(item: Any)...
# announcements
t
Why can't we just do:
Copy code
class LootBox(item: Any) {
    private var loot = item
}
Instead of
Copy code
class LootBox<T>(item: T) {
    private var loot: T = item
}
m
I think with your current example, it doesn't provide much value. If you change loot to be public, then it would
Copy code
class LootBox<T>(item: T) {
    var loot: T = item
}

val lootBox = LootBox("gold”)
val loot: String = lootBox.loot

vs

val lootBox = LootBox(“gold”)
val loot: String = lootBox.loot as String
The latter is unsafe, could cause a crash if T is not a String. The whole idea is to allow LootBox to work with whatever type you want. And allowing users of LootBox to know what type it contains
t
@Matt Rea I'm also confused what 'in' and 'out' is... I"m stuck in this book on that also
m
Some good examples of the usefulness of generics are collections. List, Map, etc
t
@Matt Rea can you explain 'in' and 'out' in simple terms?
m
I can try! In means that the type T can only be used as an input in the class. Example would be as a parameter to a function Out means that the type T can only be used as an output in the class. Example is as a return type of a function This is a good overview. Might require some knowledge of Java generics to know why they did it this way https://kotlinlang.org/docs/generics.html
I would try to play around with normal generics, get a feel for them, then tackle covariant and contravariant (out and in)
t
ok thanks
K 1
g
Good blog post about Kotlin generics and variance (in/out) https://proandroiddev.com/understanding-generics-and-variance-in-kotlin-714c14564c47
👌 1
actually there is quite a lot blogs about it, just google kotlin generics variance
t
@gildor I understand it now, after some time 🙂