Jayway
Jayway

Reputation: 3

Scala - Return a class object from a list from individual parameter

I need to return a single Book case class object from a list of Books by searching for only one of its parameters. I have it working with a foreach but wondering if I can do it more elegantly.

I had the same with other parameters ((partial) author and title searches) which I have used filter to return new lists with all matching books, but with the ISBN it can only return one object and was hoping I could do that rather than a list of 1.

I have used a foreach to loop over the entire list and update a var with the desired Book, but it feels messy.

The class looks like this:

case class Book(title: String, author: String, ISBN: String, reference: Boolean = false)

This is what I have:

  def searchISBN(isbnSearch: String): Book = {
    var result :Book = null
    books.foreach {
      book => if(book.ISBN == isbnSearch) { result = book }
    }
    result
  }

Trying things more like this:

  def searchISBN(isbnSearch: String): Book = {
    val result = books.find(_.isbnSearch)
    result
  }

Upvotes: 0

Views: 192

Answers (1)

jwvh
jwvh

Reputation: 51271

Your 2nd approach is more Scala-esque, but you have to account for the fact that the target might not be found.

def searchISBN(isbnSearch: String): Option[Book] =
  books.find(_.ISBN == isbnSearch)

Upvotes: 3

Related Questions