https://kotlinlang.org logo
t

therealbluepandabear

03/20/2021, 3:18 AM
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

Matt Rea

03/20/2021, 3:47 AM
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

therealbluepandabear

03/20/2021, 3:48 AM
@Matt Rea I'm also confused what 'in' and 'out' is... I"m stuck in this book on that also
m

Matt Rea

03/20/2021, 3:48 AM
Some good examples of the usefulness of generics are collections. List, Map, etc
t

therealbluepandabear

03/20/2021, 3:50 AM
@Matt Rea can you explain 'in' and 'out' in simple terms?
m

Matt Rea

03/20/2021, 4:07 AM
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

therealbluepandabear

03/20/2021, 4:11 AM
ok thanks
K 1
g

gildor

03/23/2021, 3:50 AM
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

therealbluepandabear

03/23/2021, 3:51 AM
@gildor I understand it now, after some time 🙂