Using scala constructs on Java collections

View: New views
3 Messages — Rating Filter:   Alert me  

Using scala constructs on Java collections

by Bastian, Mark :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Some parts of this message have been removed. Learn more about Nabble's security policy.
Is there a way to easily invoke foreach on a Java collection in a scala class?
 
Right now, all I can figure out is the old:
 
val iter = collection.iterator
while(iter.hasNext)
{
  val foo = iter.next
  foo.doIt
}
 
I'd much rather just do collection.foreach(x => x.doIt) or even be able to use the Java 5 enhanced for loop.
 
Thanks,
Mark
 

Re: Using scala constructs on Java collections

by Ricky Clarkson :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Take a look at scala.collection.jcl.Conversions.

2008/10/22 Bastian, Mark <mbastia@...>:

> Is there a way to easily invoke foreach on a Java collection in a scala
> class?
>
> Right now, all I can figure out is the old:
>
> val iter = collection.iterator
> while(iter.hasNext)
> {
>   val foo = iter.next
>   foo.doIt
> }
>
> I'd much rather just do collection.foreach(x => x.doIt) or even be able to
> use the Java 5 enhanced for loop.
>
> Thanks,
> Mark
>

Re: Using scala constructs on Java collections

by James Iry-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

scala> case class Person(name : String, age : Int)
defined class Person

scala> val people = new java.util.ArrayList[Person]
people: java.util.ArrayList[Person] = []

scala> people add Person("Bob", 42)               
res0: Boolean = true

scala> people add Person ("Toby", 13)             
res1: Boolean = true

scala> people add Person ("Sarah", 28)            
res2: Boolean = true

scala> import scala.collection.jcl.Conversions._   // this is the important bit
import scala.collection.jcl.Conversions._

scala> for (person <- people) yield person.age
res3: Seq[Int] = ArrayBufferRO(42, 13, 28)

scala> people foreach println
Person(Bob,42)
Person(Toby,13)
Person(Sarah,28)

scala> for (person <- people) println(person.name)
Bob
Toby
Sarah

scala> val (minors, adults) = people partition (_.age < 18)
minors: Iterable[Person] = ArrayBuffer(Person(Toby,13))
adults: Iterable[Person] = ArrayBuffer(Person(Bob,42), Person(Sarah,28))

On Wed, Oct 22, 2008 at 7:36 AM, Bastian, Mark <mbastia@...> wrote:
Is there a way to easily invoke foreach on a Java collection in a scala class?
 
Right now, all I can figure out is the old:
 
val iter = collection.iterator
while(iter.hasNext)
{
  val foo = iter.next
  foo.doIt
}
 
I'd much rather just do collection.foreach(x => x.doIt) or even be able to use the Java 5 enhanced for loop.
 
Thanks,
Mark