3

I've been playing around with Scala and was wondering if it's possible to nest calls (probably a bad way to describe it).

What I'm trying to do:

val nested:MyNestType =
  foo("hi") {
    foo("bye") {
      foo("done")
    }
  }

This will loop through and print out this:

"done" inside "bye" inside "hi" // or the other way around..

How could this be done using Scala?

7
  • Do you have an example in another language that shows what you want to do? Commented Jun 15, 2014 at 2:18
  • @RobbyCornelissen sure, ruby: pastebin.com/PugN6fFk Commented Jun 15, 2014 at 2:21
  • Thanks. Unfortunately my Ruby-Fu is not quite there yet. I'll have to leave it to someone else... Commented Jun 15, 2014 at 2:25
  • 1
    why the downvote? an explanation would be nice so that I could improve my question.. Commented Jun 15, 2014 at 2:54
  • +1 as a puzzler but unless you have a really good reason please don't try to write Scala code like this. Commented Jun 15, 2014 at 2:57

1 Answer 1

5

There are so many horrible ways you could do this kind of thing in Scala:

sealed trait Action { def doIt(): Unit }

class InnerAction(message: String) extends Action { def doIt() = print(message) }

class WrapperAction(message: String, inner: Action) extends Action {
  def doIt() = { inner.doIt(); print(s" inside $message") }
}

def foo(message: String)(implicit next: Action = null) =
  Option(next).fold[Action](new InnerAction(message))(action =>
    new WrapperAction(message, action)
  )

trait MyNestType

implicit def actionToMyNestType(action: Action): MyNestType = {
  action.doIt()
  println()
  new MyNestType {}
}

And then:

scala> val nested: MyNestType =
     |   foo("hi") {
     |     foo("bye") {
     |       foo("done")
     |     }
     |   }
done inside bye inside hi
nested: MyNestType = $anon$1@7b4d508f

Please don't ever do this, though. If you're writing Scala, write Scala.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.