Runner in the High

技術のことをかくこころみ

Scalaにおける無名クラスのメソッド呼び出しはリフレクションが使われる

こんなコードを書いた。

val App = new {
  def say = println("hello")
}

App.say

コレ自体実行はできるが、以下の警告がでる。

reflective access of structural type member method say should be enabled
by making the implicit value scala.language.reflectiveCalls visible.
----
This can be achieved by adding the import clause 'import scala.language.reflectiveCalls'
or by setting the compiler option -language:reflectiveCalls.
See the Scaladoc for value scala.language.reflectiveCalls for a discussion
why the feature should be explicitly enabled.

Scalaでは無名クラスにおけるメソッド呼び出しはランタイムリフレクションが使われるからである。

任意のトレイトを実装したクラスをワンショットで作りたい、などの用途では使われるケースが考えられるが、パフォーマンスや型安全性のことを考えると避けるほうが良いのかもしれない。