scala - Referencing instance member from anonymous function -


i'm trying define class instances have string , function. in function string parameter used.

class tenant(val name: string, exclusion: map[string, int] => boolean)  val rule1 = new tenant(name = "baker3",   (suggestedfloor: map[string, int]) => suggestedfloor(name) != topfloor)  val rule1 = new tenant(name = "cooper2",   (suggestedfloor: map[string, int]) => suggestedfloor(name) != groundfloor) 

which gives error on last use of name: not found: value name.

how can that?

problem:

you trying reference name name in lexical context it's not available:

val rule1 = new tenant(name = "cooper2",   (suggestedfloor: map[string, int]) => suggestedfloor(name) != groundfloor) 

name in context not refer name defined within tenant, instead name name in scope of rule1 definition, of course not exist. code, error disappear of course not want:

val name = ??? // `name` gets referenced lambda  val rule1 = new tenant(name = "cooper2",   (suggestedfloor: map[string, int]) => suggestedfloor(name) != groundfloor) 

solution:

to work around that, instead of passing in function @ time of instantiation, use method override instead:

abstract class tenant(val name: string) {   def exclusion(suggestedfloor: map[string, int]): boolean }  val rule1 = new tenant(name = "baker3") {   def exclusion(suggestedfloor: map[string, int]) =     suggestedfloor(name) != topfloor } 

this creates anonymous subclass of tenant "custom" definition exclusion; this, say, considered idiomatic style in scala.

alternatively, can resort different semantics , override not method attribute contains function instead; yield shorter syntax when combined more compact form of lambda definition using _:

abstract class tenant(val name: string) {   val exclusion: map[string, int] => boolean }  val rule1 = new tenant(name = "baker3") {   val exclusion = (_: map[string, int])(name) != topfloor } 

unfortunately, need map[string, int] re-declaration, not eliminated type inferencer, reasons people smarter me can elaborate on.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -