Scala:参数的 (a: String) 和 (a: => String) 之间有什么区别? [英] Scala: What is the difference between (a: String) and (a: => String) for argument?

查看:43
本文介绍了Scala:参数的 (a: String) 和 (a: => String) 之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法有什么区别?

What is the difference between these two method?

def method1(msg: => String) = print(msg)
def method2(msg: String) = print(msg)

我可以同时调用它们.

  method1("1")
  method2("2") 

然后他们打印 12

推荐答案

它被称为按名称传递参数,当参数按名称传递并在函数内部访问时,它会再次计算.您可以运行示例代码:

It's called passing argument by name, when argument passed by name and accessed inside function it evaluates again. You can run example code:

  def method1(msg: => String) = {
    println(msg)
    println(msg)
  }
  def method2(msg: String) = {
    println(msg)
    println(msg)
  }

  method1({println("Evaluate Arg1"); "Method1"})
  method2({println("Evaluate Arg2"); "Method2"})

输出:

Evaluate Arg1
Method1
Evaluate Arg1
Method1
Evaluate Arg2
Method2
Method2

正如你在 method1 中看到的,每次访问 msg 都会重新评估

As you can see in method1 every time you access msg it's re-evaluated

这篇关于Scala:参数的 (a: String) 和 (a: => String) 之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆