by shigemk2

当面は技術的なことしか書かない

filterで複数の条件

"scala filter multiple conditions" などでググると良い。

scala> (1 to 100).filter(_ % 3 == 0 && _ % 5== 0)
<console>:12: error: missing parameter type for expanded function ((x$1, x$2) => x$1.$percent(3).$eq$eq(0).$amp$amp(x$2.$percent(5).$eq$eq(0)))
       (1 to 100).filter(_ % 3 == 0 && _ % 5== 0)
                         ^
<console>:12: error: missing parameter type for expanded function ((x$1: <error>, x$2) => x$1.$percent(3).$eq$eq(0).$amp$amp(x$2.$percent(5).$eq$eq(0)))
       (1 to 100).filter(_ % 3 == 0 && _ % 5== 0)
                                       ^

scala> (1 to 100).filter(x => x % 3 == 0 && x % 5== 0)
res22: scala.collection.immutable.IndexedSeq[Int] = Vector(15, 30, 45, 60, 75, 90)

複数条件を指定したい場合は、_で省略せず(このアンスコはプレースホルダーという)にちゃんと書こうね、っていう話です。

stackoverflow.com

straitwalk.hatenablog.com

FileUtilsでファイル書き込みなど

【Commons】FileUtilsで1行のコードでファイル書き込み : mwSoft blog

Javaだとこんな感じらしいですが、Scalaでもほぼ同じようなことができます。

// writeStringToFileを使うと、文字列を手軽にファイルに書き込めます
// 見た限りでは追記モードはなさそう
String strData = "この文字をファイルに書き込む";
FileUtils.writeStringToFile( new File("out.txt"), strData, "utf-8" );
 
// byte[]形式で書くメソッドもあります
// 画像等、文字列以外を出力したかったり、
// HTTP通信で取ってきたものをそのまま書き込みたい時なんかにどうぞ
byte[] byteArray = strData.getBytes();
FileUtils.writeByteArrayToFile( new File("out.txt"), byteArray );