本文介绍了使用和不使用“="有什么区别?在 Scala defs 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面两个def有什么区别

def someFun(x:String) { x.length }

def someFun(x:String) = { x.length }

推荐答案

正如其他人已经指出的,前者是

As others already pointed out, the former is a syntactic shortcut for

def someFun(x:String): Unit = { x.length }

意味着 x.length 的值被丢弃,函数返回 Unit(或 (),如果你愿意).

Meaning that the value of x.length is discarded and the function returns Unit (or () if you prefer) instead.

我想强调的是,此功能已于 2013 年 10 月 29 日弃用(https://github.com/scala/scala/pull/3076/),但只有在使用 -Xfuture 标志编译时才会显示警告.

I'd like to stress out that this is deprecated since Oct 29, 2013 (https://github.com/scala/scala/pull/3076/), but the warning only shows up if you compile with the -Xfuture flag.

scala -Xfuture -deprecation

scala> def foo {}
<console>:1: warning: Procedure syntax is deprecated. Convert procedure `foo` to method by adding `: Unit =`.
       def foo {}
foo: Unit

所以你不应该使用所谓的过程语法.Martin Odersky 本人在他的 Scala Day 2013 Keynote 中指出了这一点,并且已经进行了讨论在 scala 邮件列表中.

So you should never use the so-called procedure syntax.Martin Odersky itself pointed this out in his Scala Day 2013 Keynote and it has been discussed in the scala mailing list.

语法非常不一致,初学者在学习语言时遇到这个问题是很常见的.出于这个原因,它很可能会在某个时候从语言中删除.

The syntax is very inconsistent and it's very common for a beginner to hit this issue when learning the language. For this reasons it's very like that it will be removed from the language at some point.

这篇关于使用和不使用“="有什么区别?在 Scala defs 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 12:45