在Scala函数中按名称调用参数

sca*_*ode 2 scala

我对这两个功能之间的区别有疑问:

def getFunction(checkpointPath: String,
                  sparkConf: SparkConf,
                  creatingFunc: () => StreamingContext): StreamingContext = {
    function body
  }


def getFunction(checkpointPath: String,
                  sparkConf: SparkConf,
                  creatingFunc:  => StreamingContext): StreamingContext = {
    function body
  }
Run Code Online (Sandbox Code Playgroud)

因此,按名称调用的参数是相同的:

creatingFunc:  => StreamingContext 
Run Code Online (Sandbox Code Playgroud)

creatingFunc: () => StreamingContext
Run Code Online (Sandbox Code Playgroud)

或者没有 ?

Mar*_*lic 5

两者不一样。第一种情况指定按名称调用的方法参数

creatingFunc:  => StreamingContext 
Run Code Online (Sandbox Code Playgroud)

而第二种情况指定按值传递方法参数,其中该参数恰好是类型的函数 () => StreamingContex

creatingFunc: () => StreamingContext
Run Code Online (Sandbox Code Playgroud)

例如,考虑以下两种方法

def foo(arg: () => String) = ""
def foo(arg: => String) = ""
Run Code Online (Sandbox Code Playgroud)

然后

foo(() => "") // resolves to call first foo
foo("")       // resolves to call second foo
Run Code Online (Sandbox Code Playgroud)