davidrpugh
davidrpugh

Reputation: 4573

Idiomatic to find the first element in a collection that matches a given sub-type in Scala

I am teaching myself Scala, Akka, and Play by developing a model of an order book. I need to find the first element in a collection (specifically a priority queue) of various types of Ask orders that matches a certain type of Ask order (specifically a LimitOrderAsk)

The solution that I have come up with is the following:

bestLimitOrderAsk = askBook find {
  case ask: LimitOrderAsk => true
  case _ => false
}

I am new to scala and I an not sure that this is the idiomatic Scala way to solve this problem. Thoughts?

Upvotes: 2

Views: 77

Answers (1)

dk14
dk14

Reputation: 22374

Two options:

 askBook.collectFirst{case ask: LimitOrderAsk => ask}  

or:

 askBook.find(_.isInstanceOf[LimitOrderAsk])

If you just need to know, if there is some element (with appropriate type) - add .nonEmpty at the end of expression:

 askBook.collectFirst{case ask: LimitOrderAsk => ask}.nonEmpty
 askBook.exists(_.isInstanceOf[LimitOrderAsk])

Examples:

scala> List(5, null, "aaa", "bbb").find(_.isInstanceOf[String])
res30: Option[Any] = Some(aaa)

scala> List(5, null, "aaa", "bbb").collectFirst{case a: String => a}
res31: Option[String] = Some(aaa)

Boolean result:

scala> List(5, null, "aaa").find(_.isInstanceOf[String]).nonEmpty
res32: Boolean = true

scala> List(5, null).find(_.isInstanceOf[String]).nonEmpty
res33: Boolean = false

Upvotes: 4

Related Questions