在 Scala 中省略等号的方法会变成什么? [英] What does a method turn into with the equal sign left out in Scala?

查看:42
本文介绍了在 Scala 中省略等号的方法会变成什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现在 Scala 中定义方法时可以不使用 = 符号.

I've just found out that it's possible not to use the sign of = when defining a method in Scala.

def someMethod(a: Int) {
  println(a)
  println("---------")
}

上面的版本和参数列表后面加等号和大括号{有什么区别?

What's the difference between the above version and one with the equals sign after the parameter list and the opening curly bracket {?

推荐答案

这样的方法定义被称为procedure.这是 Unit 返回方法的特殊语法:

Such method definition is called procedure. It's a special syntax for Unit-returning methods:

def someMethod(a: Int): Unit = {
  println(a)
  println("---------")
}

这不是推荐的语法.Martin Odersky 认为包含这种语法是一个错误的决定.请参阅主题演讲 - Scala 风格第 45 章.

It's not a recommended syntax. Martin Odersky believes it was a bad decision to include this syntax. See Keynote - Scala with Style chapter 45.

这篇关于在 Scala 中省略等号的方法会变成什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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