Scalaとダックタイピング
Scalaはダックタイピング的なことができる。
import Console._
case class Foo {
def hello() {
println("Foo hello.")
}
}
case class Bar {
def hello() {
println("Bar hello.")
}
}
object Test {
def test(o: {def hello()}) {
o.hello()
}
def main(args: Array[String]) {
test(Foo())
test(Bar())
}
}
FooとBarは、同じ継承ツリーには無いけど、Compound typeである{def hello()}に適合する(hello()というメソッドがありさえすれば良い)ので、test()に渡すことができる。もちろん、これってバイトコードを見るとリフレクションになるから、遅いけど。
これの面白いところは、いわゆる静的型付けの無いダックタイピングと違って、型チェックされるところだ。意図的にFooのhello()をタイプミスしてみると、
case class Foo {
def hell() {
println("Foo hello.")
}
}
ちゃんとコンパイル時に、エラー検出されるのだ。
shanai@shanai-laptop:/tmp$ scalac test.scala
test.scala:21: error: type mismatch;
found : Foo
required: AnyRef{def hello(): Unit}
test(Foo())
^
one error found
静的型付け大好き人間にとっては、これは結構シビれる。








