Scala の REPL から、無理やり Java8 を使う

まだScala側がほとんど対応してなくて、本当に無理やりです。

追記

というわけで、以下(の変なエラーがでたことに関して)は2.10.1もしくは2.11.0-M2などでの話。2.11.0-M3以降を使いましょう!



classfile読み込み時にエラー何度もでるし、AbstractMethodErrorなどもいっぱいでるので、まだ全然実用的じゃないです。でもちょっとだけ動きました。
Scala2.10.1でも、 2.11.0のSNAPSHOT でも同じでした。使ったjava8のversionは、ここからダウンロードした lambda-8-b88-linux-x64-29_apr_2013 です。

$ scala
Welcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0-ea).
Type in expressions to have them evaluated.
Type :help for more information.

scala> [init] error: error while loading CharSequence, class file '/home/kenji/jdk8/lambda-8-b88-linux-x64-29_apr_2013/jre/lib/rt.jar(java/lang/CharSequence.class)' is broken
(class java.lang.RuntimeException/bad constant pool tag 18 at byte 10)

// とりあえず最初に"bad constant pool tag"のエラーでる



scala> import java.util.function._
import java.util.function._


scala> implicit def ToBinaryOperator[A](self: (A, A) => A) = new BinaryOperator[A]{def apply(a:A,b:A):A = self(a,b) }
error: error while loading BiFunction, class file '/home/kenji/jdk8/lambda-8-b88-linux-x64-29_apr_2013/jre/lib/rt.jar(java/util/function/BiFunction.class)' is broken
(class java.lang.RuntimeException/bad constant pool tag 18 at byte 15)
<console>:10: error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement
       implicit def ToBinaryOperator[A](self: (A, A) => A) = new BinaryOperator[A]{def apply(a:A,b:A):A = self(a,b) }
                                                                                             ^
<console>:10: error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement
       implicit def ToBinaryOperator[A](self: (A, A) => A) = new BinaryOperator[A]{def apply(a:A,b:A):A = self(a,b) }
                                                                                                 ^

// まだ対応してないので、よくわからないエラー・・・



scala> implicit def ToBinaryOperator[A](self: (A, A) => A) = new BinaryOperator[A]{def apply(a:Any,b:Any):A = self(a.asInstanceOf[A],b.asInstanceOf[A]) }
??? base anonymous class $anon not found in basetypes of anonymous class $anon
??? base trait BinaryOperator not found in basetypes of anonymous class $anon
??? base <none> not found in basetypes of anonymous class $anon
warning: there were 1 feature warning(s); re-run with -feature for details
ToBinaryOperator: [A](self: (A, A) => A)java.util.function.BinaryOperator[A]{def apply(a: Any,b: Any): A}

// 相変わらずエラーでてるけど、無理やりキャスト使って定義したら、定義できた!?



scala> java.util.stream.Stream.of(1,2,3,4,5,6,7,8,9,10).reduce(0, (a: Int, b: Int) => a + b)
res0: Int = 55

// Scala の Function2型から、Java の lambda に暗黙変換できて、正しく実行できた!?