Larry OBrien
Larry OBrien

Reputation: 8606

How to instantiate and populate a Scala Stream in Java?

I have a Scala function foo(bs : Stream[Bar]) : Bat that I need to call from Java code. How do I create the "bs" Stream (Stream[Bar]) in Java and lazily generate its Bar objects?

Upvotes: 13

Views: 1894

Answers (4)

AndreasScheinert
AndreasScheinert

Reputation: 1918

I know you were looking for scala stream but there is functional java too: http://functionaljava.googlecode.com/svn/artifacts/3.0/javadoc/fj/data/Stream.html

Upvotes: 0

Travis Brown
Travis Brown

Reputation: 139038

Depending on what needs to be in the stream, it might be easiest to create a java.util.Iterator and then convert this to a Stream via a scala.collection.Iterator:

import scala.collection.JavaConverters;
import scala.collection.immutable.Stream;

...

List<String> list = new ArrayList<String>();

\\ Fill the list somehow...

Iterator<String> it = list.iterator();

Stream<String> stream = JavaConverters.asScalaIteratorConverter(it)
                                      .asScala().toStream();

The iterator doesn't have to come from a collection, of course—we can just as easily create an infinite stream by implementing our own iterator:

Stream<String> stream = JavaConverters.asScalaIteratorConverter(
  new Iterator<String>() {
    int i = 0;
    public boolean hasNext() { return true; }
    public void remove() { throw new UnsupportedOperationException(); }
    public String next() { return Integer.toString(i++); }
  }
).asScala().toStream();

It's not as pretty as something like Stream.iterate(0)(_ + 1).map(_.toString), but it works.

Upvotes: 8

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297185

The best way is to use one of the factories available on Stream object companion. For the most useful of them, you'll need to implement Function1 as well, which can be done by extending AbstractFunction1.

Here's an example:

import scala.collection.immutable.Stream;
import scala.runtime.AbstractFunction1;

public class Ex {
    public Stream<Integer> stream = Stream.iterate(0, new Increment());
}

class Increment extends AbstractFunction1<Integer, Integer> {
    public Integer apply(Integer v1) {
        return v1 + 1;
    }
}

Upvotes: 10

Jens Schauder
Jens Schauder

Reputation: 81907

Have you tried

scala.collection.immutable.Stream bs = new scala.collection.immutable.Stream()

?

Upvotes: 0

Related Questions