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/b2aa16dae9fa2be2ef0473065027db74 to your computer and use it in GitHub Desktop.
Save espio999/b2aa16dae9fa2be2ef0473065027db74 to your computer and use it in GitHub Desktop.
defining container with Any type, it sometime requires type cast.
//any型
//どのような型でも受け取るコンテナ
class Container(var value: Any)
//どのような型でも受取、コンテナに詰める
fun packer(value: Any): Container{
return Container(value)
}
//コンテナの中身を確認する
fun officer(containers: List<Container>){
for(item in containers){
println("value = ${item.value}")
}
}
fun main() {
val intContainer = Container(100)
val strContainer = Container("hello")
//要キャスト
val i: Int = intContainer.value as Int
val s: String = strContainer.value as String
println("i = ${i}")
println("s = ${s.uppercase()}")
var containers: List<Container> = 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