LoginSignup
2
2

More than 5 years have passed since last update.

Scala2.10 Implicit Class

Last updated at Posted at 2014-11-17

Implicit Classとは

Scalaでは暗黙の型変換を使用し、継承を使わず型を拡張したかのように扱うことができます。
そのためには変換後のクラスと変換用のメソッドが必要だったのですが、Scala2.10から変換後のクラスと変換用のメソッドを用意しなくても、直感的に暗黙の型変換を記述できるImplicit Classが導入されました。

Implicit Classは、クラス宣言にimplicitキーワードを付与します。

◆java.io.FIleを拡張するImplicit Class
~~~
implicit class ReadFile(file: java.io.File) {
def asString: String = {
// ファイルの内容を読み込んで文字列を返す
}
}

// implicit Classで定義したメソッドを使用
val file = new java.io.File("sample.scala")
plintln(file.asString)
~~~

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2