8

I like the way, you can write one-liner-methods in Scala, e.g. with List(1, 2, 3).foreach(..).map(..).

But there is a certain situation, that sometimes comes up when writing Scala code, where things get a bit ugly. Example:

def foo(a: A): Int = {
  // do something with 'a' which results in an integer
  // e.g. 'val result = a.calculateImportantThings

  // clean up object 'a'
  // e.g. 'a.cleanUp'

  // Return the result of the previous calculation
  return result
}

In this situation we have to return a result, but can not return it directly after the calculation is done, because we have to do some clean up before returning.

I always have to write a three-liner. Is there also a possibility to write a one-liner to do this (without changing the class of A, because this may be a external library which can not be changed) ?

5
  • 2
    If the operations on 'a' are always the same, why not wrap them into a function? Jul 9, 2012 at 9:01
  • 4
    in addition to Vinc' comment: one-liners don't play well with imperative code.
    – ziggystar
    Jul 9, 2012 at 9:10
  • 3
    Your introductory example is wrong: you can't do List(1, 2, 3).foreach(..).map(..) because foreach returns Unit. Also I want to add to ziggystar's comment: hunting for one-liners while writing imperative code is just wrong and will get you nowhere, because it simply violates the essence of imperative programming paradigm. Jul 9, 2012 at 10:38
  • You need some library for extending functions combination. Like PEAK library for python. I've searched for one and found none. May be you would be lucky
    – ayvango
    Jul 9, 2012 at 11:00
  • 2
    The cheeky answer to the question is to just use semicolons to cram it onto one line: def foo(a : A): Int = { val result = a.calculateImportantThings; a.cleanup; result }. I mean, that's what semicolons are for, right? To combine side-effecting actions by sequencing them.
    – Dan Burton
    Jul 9, 2012 at 21:59

6 Answers 6

9

There are clearly side-effects involved here (otherwise the order of invocation of calculateImportantThings and cleanUp wouldn't matter) so you would be well advised to reconsider your design.

However, if that's not an option you could try something like,

scala> class A { def cleanUp {} ; def calculateImportantThings = 23 }
defined class A

scala> val a = new A
a: A = A@927eadd

scala> (a.calculateImportantThings, a.cleanUp)._1
res2: Int = 23

The tuple value (a, b) is equivalent to the application Tuple2(a, b) and the Scala specification guarantees that its arguments will be evaluated left to right, which is what you want here.

6
  • This is really one liner, not a workaround as others propose!
    – Yaroslav
    Jul 9, 2012 at 9:35
  • 2
    I vote this as "rather cryptic code"; relying on some pretty unimportant (and thus unknown) part of the scala specification.
    – ziggystar
    Jul 9, 2012 at 9:55
  • 1
    @ziggystar You think evaluation order is an unimportant part of the Scala specification?!? Jul 9, 2012 at 10:52
  • 2
    @ziggystar The one-liner would be def foo(a:A):Int = (a.calculateImportantThings, a.cleanup)._1. I don't consider this cryptic at all: the reader can clearly see that since ._1 is invoked immediately, the only reason to put the two values in a tuple in the first place is to perform both effects.
    – Dan Burton
    Jul 9, 2012 at 10:55
  • 2
    @MilesSabin All code I wrote up until know did not rely on evaluation order and I don't plan to write code that does in the near future. So to me, this detail has been unimportant. Indeed I paused a bit before writing "unimportant", as I meant unimportant to the majority of code written.
    – ziggystar
    Jul 9, 2012 at 11:20
7

This is a perfect use-case for try/finally:

try a.calculateImportantThings finally a.cleanUp

This works because try/catch/finally is an expression in scala, meaning it returns a value, and even better, you get the cleanup whether or not the calculation throws an exception.

Example:

scala> val x = try 42 finally println("complete")
complete
x: Int = 42
2
  • 1
    Fascinating! I wouldn't consider this an abuse in the least, especially since you probably want to a.cleanup even if a.calculateImportantThings throws an exception. If anything, I'd say this use case is the very reason that try/catch/finally is an expression in Scala.
    – Dan Burton
    Jul 9, 2012 at 21:53
  • Dan, you are right, on reflection this is a perfect use-case for try/finally! Wording ajusted. Jul 14, 2012 at 5:41
5

There is, in fact, a Haskell operator for just such an occasion:

(<*) :: Applicative f => f a -> f b -> f a

For example:

ghci> getLine <* putStrLn "Thanks for the input!"
asdf
Thanks for the input!
"asdf"

All that remains then is to discover the same operator in scalaz, since scalaz usually replicates everything that Haskell has. You can wrap values in Identity, since Scala doesn't have IO to classify effects. The result would look something like this:

import scalaz._
import Scalaz._

def foo(a: A): Int = 
  (a.calculateImportantThings.pure[Identity] <* a.cleanup.pure[Identity]).value

This is rather obnoxious, though, since we have to explicitly wrap the side-effecting computations in Identity. Well the truth is, scalaz does some magic that implicitly converts to and from the Identity container, so you can just write:

def foo(a: A): Int = Identity(a.calculateImportantThings) <* a.cleanup()

You do need to hint to the compiler somehow that the leftmost thing is in the Identity monad. The above was the shortest way I could think of. Another possibility is to use Identity() *> foo <* bar, which will invoke the effects of foo and bar in that order, and then produce the value of foo.

To return to the ghci example:

scala> import scalaz._; import Scalaz._
import scalaz._
import Scalaz._

scala> val x : String = Identity(readLine) <* println("Thanks for the input!")
<< input asdf and press enter >>
Thanks for the input!
x: String = asdf
1
  • 3
    Let me take this opportunity to say I love your Haskell+Scala answers. Jul 9, 2012 at 21:09
5

Maybe you want to use a kestrel combinator? It is defined as follows:

Kxy = x

So you call it with the value you want to return and some side-effecting operation you want to execute.

You could implement it as follows:

def kestrel[A](x: A)(f: A => Unit): A = { f(x); x }

... and use it in this way:

kestrel(result)(result => a.cleanUp)

More information can be found here: debasish gosh blog.

[UPDATE] As Yaroslav correctly points out, this is not the best application of the kestrel combinator. But it should be no problem to define a similar combinator using a function without arguments, so instead:

f: A => Unit

someone could use:

f: () => Unit
1
  • 1
    Well, it can be used here but it isn't the best application of the kestrel combinator, cause it's designed to return a value on which side-effects are executed, while it is needed to return a result of some of those side-effects.
    – Yaroslav
    Jul 9, 2012 at 9:55
2
class Test {
  def cleanUp() {}
  def getResult = 1
}

def autoCleanup[A <: Test, T](a: A)(x: => T) = {
  try { x } finally { a.cleanUp }
}  

def foo[A <: Test](a:A): Int = autoCleanup(a) { a.getResult }


foo(new Test)

You can take a look at scala-arm project for type class based solution.

3
  • He asked for a one liner, not for an auto cleanup solution.
    – Yaroslav
    Jul 9, 2012 at 9:38
  • 2
    He NEED an auto cleanup solution.
    – xiefei
    Jul 9, 2012 at 10:04
  • Where did he asked for it? In the example. What does it mean? That instead of cleanUp may be anyOtherMethod.
    – Yaroslav
    Jul 9, 2012 at 10:30
0

Starting Scala 2.13, the chaining operation tap can be used to apply a side effect (in this case the cleanup of A) on any value while returning the original value untouched:

def tap[U](f: (A) => U): A


import util.chaining._

// class A { def cleanUp { println("clean up") } ; def calculateImportantThings = 23 }
// val a = new A
val x = a.calculateImportantThings.tap(_ => a.cleanUp)
// clean up
// x: Int = 23

In this case tap is a bit abused since we don't even use the value it's applied on (a.calculateImportantThings (23)) to perform the side effect (a.cleanUp).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.