Question

I have two functions. One is masterChecker, wich takes as argument an Int x and a function p, and return the boolean result p(x). Simple like that.

def masterChecker(x: Int, p: Int => Boolean): Boolean = p(x)

Then I have a second function childChecker, which is like an alias to masterChecker

def childChecker(x: Int, f: Int => Boolean): Boolean = masterChecker(x , f)

Is there any way to change f in the masterCheker call on childChecker, in a manner that it would run like !f ? (if f return true, than make it false)

Like:

// inside childChecker
masterChecker(x, !f)

I know that I could do it on the masterChecker call with !masterChecker(x,f), but what I want to know is if it´s possible to change a function behavior passed as an argument.

Was it helpful?

Solution

Sure, you can use an anonymous function like so:

 def childChecker(x: Int, f: Int => Boolean) = masterCheck(x, !f(_))

and there you go!

Even more so, you could do a number of things if you want to "modify" f within the function scope of childChecker:

 def childChecker(x: Int, f: Int => Boolean) ={
   def proxy(x: Int): Boolean ={
     val y: Int = //do things
     f(y) //see? "y" not "x"
   }

   masterCheck(x, proxy)
 }

that's part of the fun when you're dealing with plain ol' functions. Granted, this "modification" is more of a decorator pattern but it does adhere to the interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top