Gamar Mustafa
05/14/2024, 5:58 AMAny
and T
? I'm having difficulty wrapping my head around this.hfhbd
05/14/2024, 6:20 AMGamar Mustafa
05/14/2024, 7:12 AMfun main() {
val box = Box(1, "a")
val box2 = Box2(4, "x")
}
class Box<T>(t1: T, t2: T)
class Box2(t1: Any, t2: Any)
Like in this case, I used T two times, but I could give different types of objects. So why would I use T instead of Any in this case?hfhbd
05/14/2024, 7:31 AMInt
and String
is Any
.
But in practice, you rarely need unconstrained generic types but some upper type to access its members without casts.Gamar Mustafa
05/14/2024, 8:24 AMmohamed rejeb
05/14/2024, 8:46 AMCloseable
and you can use close
method from Closeable
interface.
interface Closeable {
fun close()
}
class Box<T: Closeable>(t1: T, t2: T) {
fun close() {
t1.close()
t2.close()
}
}
Gamar Mustafa
05/14/2024, 9:17 AMclass Box(val t1: Closeable,val t2:Closeable)
?mohamed rejeb
05/14/2024, 9:24 AMinterface Model {
val id: String
}
data class User(
override val id: String,
val name: String,
val email: String,
) : Model
data class State<T: Model>(
val isLoading: Boolean = false,
val isFailure: Boolean = false,
val isSuccess: Boolean = false,
val data: T,
)
val state = State<User>(data = user)
val data = state.data // type User
data.name // We can access user properties without getting errors
Here state.data
will be of type User
, you can’t get this smart casting without generics.
data class State(
val isLoading: Boolean = false,
val isFailure: Boolean = false,
val isSuccess: Boolean = false,
val data: Model,
)
val state = State(data = user)
val data = state.data // type Model not User -> can't access User properties
data.name // Unresolved reference: name
Same for Any.edrd
05/14/2024, 1:38 PMedrd
05/14/2024, 1:41 PMclass Container<T>(private val value: T) {
fun get(): T = value
}
Then you can use it like so:
val container = Container("Some string")
// This type will be String, so you can call any String methods on it. If you had "Any", that wouldn't be possible (except with casting, but that can be unsafe)
val valueInContainer = container.get()
mohamed rejeb
05/14/2024, 1:45 PMGamar Mustafa
05/14/2024, 1:48 PMclass Container2(val value: Any) {
fun get(): Any = value
}
val container2 = Container("Some string")
val valueInContainer2 = container2.get()
hfhbd
05/14/2024, 1:49 PMvalueInContainer2.length
does not compileGamar Mustafa
05/14/2024, 1:50 PMmohamed rejeb
05/14/2024, 1:51 PMGamar Mustafa
05/14/2024, 1:51 PMGamar Mustafa
05/14/2024, 1:52 PM