Skip to content

Instantly share code, notes, and snippets.

@espio999
Created October 3, 2022 00:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save espio999/2ead9175a849269a8fb3775ef105c87f to your computer and use it in GitHub Desktop.
Save espio999/2ead9175a849269a8fb3775ef105c87f to your computer and use it in GitHub Desktop.
defining container with generics type, it doesn't require type cast.
//ジェネリクス
//どのような型でも受け取るコンテナ
class Container<T>(val value: T)
//どのような型でも受け取る関数
fun <T> packer(value: T): Container<T>{
return Container(value)
}
//コンテナの中身を確認する
//out Anyで変位指定を解除→あらゆる代入を許可
fun officer(containers: List<Container<out Any>>){
for(item in containers){
println("value = ${item.value}")
}
}
fun main() {
val intContainer = Container(100)
val strContainer = Container("hello")
//キャスト不要
val i: Int = intContainer.value
val s: String = strContainer.value
println("i = ${i}")
println("s = ${s.uppercase()}")
//out Anyで変位指定を解除→あらゆる代入を許可
var containers: List<Container<out Any>> = emptyList()
containers += packer(100)
containers += packer("amazon")
containers += packer(false)
officer(containers)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment