harry callahan
harry callahan

Reputation: 121

How to implement this filtering on List

I have the following list of objects:-

case class Account(id: Long, locked: Boolean)

val a1 = Account(1, false)
val a2 = Account(2, false)
val a3 = Account(3, true)
val a4 = Account(4, true)

val accounts = List(a1, a2, a3, a4)

And here is a method which is working correctly.

def getAccounts(includeLocked: Boolean): List[Account] = {
  if(includeLocked) {
    accounts.filter(acc => acc.locked == false)
  } else {
    accounts
  }
}

Invoking getAccounts(false) correctly filters out locked Accounts and getAccounts(false) returns everything which is what I want.

getAccounts(false)
List(Account(1,false), Account(2,false))

getAccounts(true)
List(Account(1,false), Account(2,false), Account(3,true), Account(4,true))

But is there a more idiomatic way of implementing getAccounts?
My current if(includeLocked) approach feels rather clunky.

Upvotes: 0

Views: 108

Answers (1)

Leo C
Leo C

Reputation: 22439

As commented by others, it looks like if(includeLocked) should be if(!includeLocked) in your sample code.

A more concise version could be like the following:

def getAccounts(includeLocked: Boolean): List[Account] =
  accounts.filter(acc => includeLocked || !acc.locked)

getAccounts(true)
// res1: List[Account] = List(Account(1,false), Account(2,false), Account(3,true), Account(4,true))

getAccounts(false)
// res2: List[Account] = List(Account(1,false), Account(2,false))

Note that if/else (or pattern match) might be more verbose, it's probably more intuitive to read though.

Upvotes: 1

Related Questions