scala 引用java list,我可以直接在Java中使用scala List吗?

Can I use scala List in Java, like :

import scala.collection.immutable.List;

class HelloScalaList {

public static void main (String[] args) {

List xs = List(1, 2, 3);

System.out.println(xs);

}

}

It does not seem to compile. can't find List$.apply method.

when I change it to

List xs = Dir.ls()

where Dir is my scala class, and ls() returns a scala List, the compiler complaints about

"Internal compiler error: java.lang.ClassCastException: org.eclipse.jdt.internal.compiler.lookup.BaseTypeBinding

cannot be cast to org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding at

org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.initializeTypeVariable(BinaryTypeBinding.java:927)"

which I have no idea what it means.

I want to write some library in scala, but would also like it to be used in Java.

In my scala class there are methods that return scala List, for java code to use them, I have two options:

use scala List in java directly

write a wrapper class that returns java.util.List for those methods.

I'd rather like option 1, because otherwise I'll have to write a wrapper class for nearly ALL my scala classes.

But I just can't get scala List running in Java.

解决方案

A little java-side helper method does the trick:

import scala.collection.immutable.List;

import scala.collection.immutable.List$;

import scala.collection.immutable.$colon$colon;

public class HelloScalaList {

public static void main (String[] args) {

List xs = list(1,2,3);

System.out.println(xs);

}

public static List list(T ... ts) {

List result = List$.MODULE$.empty();

for(int i = ts.length; i > 0; i--) {

result = new $colon$colon(ts[i - 1], result);

}

return result;

}

}

[Update]

As a result of this question, I started a little project called "Scava" in order to support calls from Java to Scala: http://code.google.com/p/scava-org/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值