Clojure's 'let' equivalent in Scala

后端 未结 6 1971
不思量自难忘°
不思量自难忘° 2020-12-29 22:50

Often I face following situation: suppose I have these three functions

def firstFn: Int = ...
def secondFn(b: Int): Long = ...
def thirdFn(x: Int, y: Long, z:         


        
6条回答
  •  醉梦人生
    2020-12-29 23:35

    Here's an option you may have overlooked.

    def calculate(a: Long)(i: Int = firstFn)(j: Long = secondFn(i)) = thirdFn(i,j,j+a)
    

    If you actually want to create a method, this is the way I'd do it.

    Alternatively, you could create a method (one might name it let) that avoids nesting:

    class Usable[A](a: A) {
      def use[B](f: A=>B) = f(a)
      def reuse[B,C](f: A=>B)(g: (A,B)=>C) = g(a,f(a))
      // Could add more
    }
    implicit def use_anything[A](a: A) = new Usable(a)
    
    def calculate(a: Long) =
      firstFn.reuse(secondFn)((first, second) => thirdFn(first,second,second+a))
    

    But now you might need to name the same things multiple times.

提交回复
热议问题