Skip to content

Instantly share code, notes, and snippets.

@octonato
Last active December 29, 2016 23:09
Show Gist options
  • Save octonato/265ef9d01d71096a2099b0c54d23d242 to your computer and use it in GitHub Desktop.
Save octonato/265ef9d01d71096a2099b0c54d23d242 to your computer and use it in GitHub Desktop.
/*
Conditional function application.
!!!NOTE!!!
This not equivalent to PartialFunction as it applies a Function from T => T. The intention is to update T, not to transform.
Thus not to be used as replacement of PartialFunction.
Useful when we need to apply different conditional updates and
track if the value was changed or not at the end.
*/
object pack {
sealed trait Value[T] {
def get: T
def when[A](pred: => Boolean)(func: T => T): Value[T] = {
if (pred) Changed(func(get)) else this
}
}
object Value {
def apply[T](any: T): Value[T] = Unchanged(any)
implicit class ValueWrap[A](any: A) {
def when(pred: => Boolean)(func: A => A): Value[A] =
Value(any).when(pred)(func)
}
}
case class Changed[T](get: T) extends Value[T]
case class Unchanged[T](get: T) extends Value[T]
}
case class Person(name: String, age: Int)
import pack._
import pack.Value._
val myself = Person(name = "Renato", age = 41)
myself
.when(true) {
_.copy(name = "Renato Cavalcanti")
}
.when(false) {
_.copy(age = 42)
}
myself
.when(false) {
_.copy(name = "Renato Cavalcanti")
}
.when(false) {
_.copy(age = 42)
}
@octonato
Copy link
Author

defined object pack
defined class Person
import pack._
import pack.Value._
myself: Person = Person(Renato,41)
res31: Person = Person(Renato,41)
res32: pack.Value[Person] = Changed(Person(Renato Cavalcanti,41))
res33: pack.Value[Person] = Changed(Person(Renato Cavalcanti,41))
res34: Person = Person(Renato,41)
res35: pack.Value[Person] = Unchanged(Person(Renato,41))
res36: pack.Value[Person] = Unchanged(Person(Renato,41))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment