Vikas Pandya Vikas Pandya - 3 months ago 11
Scala Question

apply multiple filter conditions and produce only one element from a list

say for e.g.

scala> case class Entitlement(read: Boolean, edit: Boolean, create: Boolean, delete: Boolean)
defined class Entitlement

scala> List (Entitlement(read= true, edit = true, create= false, delete =false),Entitlement(read= true, edit = false, create= false, delete =false),Entitlement(read= true, edit = true, create= false, delete =true))
res0: List[Entitlement] = List(Entitlement(true,true,false,false),
Entitlement(true,false,false,false), Entitlement(true,true,false,true))


Is there a way to create ONE and ONLY one
Entitlement(true,true,false,true)
with a single pass of a List
res0
such that it'll go thru the list and if
read=true
found that's the final
read
privilege
else default value for read=false
- if
edit=true
found that's the final
edit
privilege
else default value for edit=false
and so on. in this toy example
create=false
in all of the
Entitlement
elements in the
List
why final result will be

Entitlement(true,true,false,true)

Answer

You can fold your list and or together the corresponding values of the Entitlements. You start with an Entitlement with all values set to false.

res0.fold(Entitlement(false, false, false, false))((e1, e2) => 
    Entitlement(
        e1.read || e2.read, 
        e1.edit || e2.edit, 
        e1.create || e.create,
        e1.delete || e2.delete))
Comments