<< 2008/05/20 | Home | 2008/05/22 >>
PR: 転職    葬式    マンスリーマンション 神戸    北海道    環境    FX    不動産担保融資    桐ヶ谷斎場    海外旅行    専門学校   

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

静的型付け大好き人間にとっては、これは結構シビれる。

このサイトの掲載内容は私自身の見解であり、必ずしもIBMの立場、戦略、意見を代表するものではありません。
日本アイ・ビー・エム 花井 志生 Since 1997.6.8