Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: method within a method

Tags:

scala

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?

like image 400
goo Avatar asked Apr 19 '26 04:04

goo


1 Answers

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.

like image 108
Travis Brown Avatar answered Apr 20 '26 22:04

Travis Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!