Skip to content

Instantly share code, notes, and snippets.

@tilakpatidar
Last active April 15, 2017 07:34
Show Gist options
  • Save tilakpatidar/7c8775ac764df05abd09097588d79525 to your computer and use it in GitHub Desktop.
Save tilakpatidar/7c8775ac764df05abd09097588d79525 to your computer and use it in GitHub Desktop.
Describes the usage of non-strict functions in scala using lazy and => syntax.
//passing functions as params and executing them when required
def if2[A](cond: Boolean, onTrue: () => A, onFalse: () => A): A ={
if (cond) onTrue() else onFalse()
}
//=> using arrow syntax pass params as unevaluated but they will be
//evaluated once they are referenced no need to mention () to execute them
def if2[A](cond: Boolean, onTrue: => A, onFalse: => A): A ={
if (cond) onTrue else onFalse
}
def maybeTwice(b: Boolean, i: => Int) = {
if (b) i+i else 0
}
val x = maybeTwice(true, { println("hi"); 1+41 })
//hi
//hi
//x: Int = 84
//Using lazy with => syntax you can pass functions unevaluated and return values
//unevaluated which will be evaluated once referenced
def maybeTwice2(b: Boolean, i: => Int) = {
lazyvalj = i
if (b) j+j else 0
}
//maybeTwice: (b: Boolean, i: => Int)Int
val x = maybeTwice2(true, { println("hi"); 1+41 })
//hi
//x: Int = 84
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment