開発環境
- macOS Mojave - Apple (OS)
- Windows 10 Pro (OS)
- IntelliJ IDEA CE(Community Edition) (IDE(統合開発環境))
- Kotlin (プログラミング言語)
Head First Kotlin: A Brain-Friendly Guide (Dawn Griffiths(著)、David Griffiths(著)、O'Reilly Media)のChapter 10(generics - Know Your Ins from Your Outs)、BE the Compiler(311)の解答を求めてみる。
コード
// Aはコンパイルできない、(関数の引数には使えない)
// Bはコンパイルできる
interface B<out T> {
val x: T
fun myFunction(): T
}
// Cはコンパイルできない(プロパティがvarの場合は指定できない。)
// D はコンパイル可能
interface D<out T> {
fun myFunction(str: String): T
}
abstract class E<out T>(t: T) {
val x = t
}
class MyClass : E<Int>(10), B<Int>, D<String> {
override fun myFunction(): Int {
return x
}
override fun myFunction(str: String): String {
return "MyClass: $str"
}
}
fun main() {
val a = MyClass()
println(a.myFunction())
println(a.myFunction("Hello"))
}入出力結果
10 MyClass: Hello Process finished with exit code 0
0 コメント:
コメントを投稿