pattern matching - Scala: Dynamic selection criteria as a method argument -



pattern matching - Scala: Dynamic selection criteria as a method argument -

my intention create function in scala accepts kind of dynamic query (similar case expressions in pattern matching) , returns matching instances within list. suppose list consists of instances of case class person has few properties different types. function should able take dynamic combination of values of fields, , homecoming matching persons. looking clean solution. 1 possible ways utilize such function pass object anonymous type query (the "pattern"):

def find(?): list<person> = { ? } val matches = find(new { val name = "name"; val gender = gender.male })

ideally, develop clean way of passing conditions, instead of concrete values, it's not essential. since learning scala, not aware of techniques implement such thing. in c#, used anonymous type (similar sec line of code above) , dynamic parameters accomplish similar. clean , elegant solution in scala?

i'm not sure if looking let's seek way:

first, define person case class person(name: string, gender: gender.value) gender defined enum.

then create query case class has same fields, options default none, , method comparing query person:

case class query(name: option[string] = none, gender: option[gender.value] = none){ def ===(person: person) = check(person.name, name) && check(person.gender, gender) private def check[t](field: t, q: option[t]) = field == q.getorelse(field) }

unfortunately, in solution === has phone call check separately each field. let's leave now. maybe sufficient (because, example, list of fields not change).

note check returns true if query's alternative none, sot don't have pass fields of query:

val q = query(name = some("ann")) // gender not of import q === person("ann", gender.female) // returns true

and find method:

def find(people: list[person], query: query) = people.filter(query === _)

scala pattern-matching anonymous-types

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -