How can I programmatically make methods chainable?

前端 未结 4 1522
栀梦
栀梦 2021-02-09 05:30

Let\'s say I have a class and I want to make its methods chainable, I could do something like this:

class MyClass {

  def methodOne(arg1: Any): MyClass = {
             


        
4条回答
  •  长发绾君心
    2021-02-09 06:17

    I know this isn't probably exactly what you're looking for, but your description reminds me a lot of the doto construct in Clojure.

    I found a couple of threads discussing the different ways of porting doto to Scala:

    something like Clojure's "doto"?

    Re: something like Clojure's "doto"? (I think this was actually a reply to the first thread that somehow ended up as a separate thread)

    Looking through those threads, it looks like the easiest way is just to make a val with a short name and use that as the receiver of repeated statements.

    Or create an implicit value class (available in Scala 2.10):

    implicit class Doto[A](val value: A) extends AnyVal {
      def doto(statements: (A => Any)*): A = {
        statements.foreach((f: A => Any) => f(value))
        value
      }
    }
    new MyClass2().doto(_.methodOne(3), _.methodTwo("x"));
    

    The other answers are much more what you're looking for, but I just wanted to point out an alternate approach another language took for working around non-chainable method calls.

提交回复
热议问题