何时在 Scala 方法声明中使用等号? [英] When to use the equals sign in a Scala method declaration?

查看:47
本文介绍了何时在 Scala 方法声明中使用等号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

带等号:

object HelloWorld {
  def main(args: Array[String]) = {
    println("Hello!")
  }
}

不带等号:

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello!")
  }
}

以上两个程序的执行方式相同.在博客文章我不知道的事情就像在 Scala 中一样,我读到当缺少等号时,该方法将返回 Unit(与 Java 的 void 相同),因此方法返回值必须使用等号.但是不返回值的方法可以用任何一种方式编写.

Both of the above programs execute the same way. In the blog post Things I do not like in Scala I read that when the equals sign are missing, the method will return Unit (same as Java's void), so methods that return a value must use the equals sign. But methods that don't return a value can be written either way.

在不返回值的 Scala 方法中使用等号的最佳做法是什么?

What is the best practice for using the equals sign in Scala methods that don't return a value?

推荐答案

实际上,我非常不同意 Daniel 的观点.我认为不应该永远使用不等式语法.如果您的方法作为 API 公开,并且您担心不小心返回错误的类型,请添加显式类型注释:

I actually disagree pretty strongly with Daniel. I think the non-equal syntax should never be used. If your method is being exposed as an API and you're worried about accidentally returning the wrong type, add an explicit type annotation:

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println("Hello!")
    123
  }
}

non-equal 语法更短,可能看起来更干净",但我认为它只会增加混淆的可能性.有时我忘记添加等号,并认为我的方法在实际返回 Unit 时返回了一个值.因为 non-equal 和 equal-with-inferred-type 语法在视觉上非常相似,所以很容易错过这个问题.

The non-equal syntax is shorter and might look "cleaner", but I think it just adds the possibility of confusion. I have sometimes forgotten to add an equal sign and believed my method was returning a value when actually it was returning Unit. Because the non-equal and equal-with-inferred-type syntaxes are so visually similar, it's easy to miss this problem.

尽管这让我付出了更多的努力,但我更喜欢显式类型注释,因为它们很重要(即暴露的接口).

Even though it costs me a little more work, I prefer the explicit type annotations when they matter (namely, exposed interfaces).

这篇关于何时在 Scala 方法声明中使用等号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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