ripper234
ripper234

Reputation: 229998

How to get a single item of a Java list in scala?

I have a java.util.list that is supposed to contain exactly one item.

I want to extract this one item, and assert/assume this condition.

I could write something like this:

def single[T](list : java.util.List[T]) : T = {
    assume(list.size() == 1)
    list.get(0)
}

Is there something more idiomatic?

Upvotes: 1

Views: 731

Answers (1)

axel22
axel22

Reputation: 32335

You can use JavaConversions and the head method:

import scala.collection.JavaConverters._

def single[T](list : java.util.List[T]) : T = {
  assume(list.size == 1)
  list.asScala.head
}

Upvotes: 3

Related Questions