Created
October 3, 2022 00:56
-
-
Save espio999/b2aa16dae9fa2be2ef0473065027db74 to your computer and use it in GitHub Desktop.
defining container with Any type, it sometime requires type cast.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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