Created
October 3, 2022 00:56
-
-
Save espio999/2ead9175a849269a8fb3775ef105c87f to your computer and use it in GitHub Desktop.
defining container with generics type, it doesn't require 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
//ジェネリクス | |
//どのような型でも受け取るコンテナ | |
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