廃止予定警告 warning: there were deprecation warnings; re-run with -deprecation for details

Scalaをいじっていたら、以下のような警告が出た時のお話。

warning: there were deprecation warnings; re-run with -deprecation for details

こんな感じに警告が出ました。

scala> List(1,2,3).sort(_<_).first
warning: there were deprecation warnings; re-run with -deprecation for details
res0: Int = 3

調べてみると・・・

廃止予定のメソッドを今更使っちゃダメだよ〜と怒られているみたい。

一般的論として、Scala 2.7 コレクションの古い機能はそのまま残っているはずだ。機能の中には廃止予定となったものもあり、それは今後のリリースで撤廃されるということだ。Scala 2.8 でそのような機能を使ったコードをコンパイルすると廃止予定警告 (deprecation warning) が発生する。その意味や性能特性を変えて 2.8 に残った演算もあり、その場合は廃止予定にするのは無理だった。このような場合は 2.8 でコンパイルすると移行警告 (migration warning) が出される。コードをどう変えればいいのかも提案してくれる完全な廃止予定警告と移行警告を得るには、-deprecation と -Xmigration フラグを scalac に渡す (-Xmigration は X で始まるため、拡張オプションであることに注意)。同じオプションを scala REPL に渡すことで対話セッション上で警告を得ることができる。

Scala 2.8 コレクション API -- Scala 2.7 からの移行

とりあえず、オプション付けて起動してみた

$ scala -deprecation -Xmigration
Welcome to Scala version 2.8.1.final (Java HotSpot(TM) Client VM, Java 1.6.0_21).
Type in expressions to have them evaluated.
Type :help for more information.

で、先ほど怒られたやつをもう一度実行してみる

scala> List(1,2,3).sort(_>_).first
<console>:6: warning: method first in trait IterableLike is deprecated: use `head' instead
       List(1,2,3).sort(_>_).first
                             ^
<console>:6: warning: method sort in class List is deprecated: use `sortWith' instead
       List(1,2,3).sort(_>_).first
                   ^
res0: Int = 3

どうやら、firstではなくhead、sortではなくsortWithを使えと。

headを使うと・・・

scala> List(1,2,3).sort(_>_).head
<console>:6: warning: method sort in class List is deprecated: use `sortWith' instead
       List(1,2,3).sort(_>_).head
                   ^
res1: Int = 3

sortWithも使うと・・・

scala> List(1,2,3).sortWith(_>_).head
res2: Int = 3

というわけで、無事に警告が消えた。