Reputation: 2280
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?
Upvotes: 3
Views: 108
Reputation: 139058
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.
Upvotes: 5