Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Created April 10, 2016 20:12
Show Gist options
  • Select an option

  • Save malcolmgreaves/cc17399bd8077882946ddedeea8da3d2 to your computer and use it in GitHub Desktop.

Select an option

Save malcolmgreaves/cc17399bd8077882946ddedeea8da3d2 to your computer and use it in GitHub Desktop.
Adds a convenient method to perform a side effect and evaluate to the (originally called) value.
implicit class ChainSideEffect[T](private val x: T) extends AnyVal {
@inline def sideEffect(op: () => Unit): T = {
val _: Unit = op()
x
}
}
@malcolmgreaves
Copy link
Author

I wrote this implicit class + method to solve a problem I had earlier today. My code looked like the following:

for {
  ...
  (closeableThing, x, y, z) <- someCoolFunction(...)
  ...
} yield MakeThisObject(
    field1 = ...,
    ...,
    fieldK = ...
  // handy! =D
  ).sideEffect(() => closeableThing.close())

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