Scala 为什么在方法名的末尾有空格以运算符结尾?

Scala 为什么在方法名的末尾有空格以运算符结尾?,scala,Scala,我最近学习了Scala,了解到对于方法名,如果方法名以运算符符号结尾(例如为类定义一元字符),并且我们指定返回类型,那么在方法的最后一个字符和:之间需要一个空格,让我们指定返回类型 def unary_-: Rational = new Rational(-numer, denom) scala> def test_-: Int = 1 // the method name is `test_-:` <console>:1: error: '=' expected but

我最近学习了Scala,了解到对于方法名,如果方法名以运算符符号结尾(例如为类定义一元字符),并且我们指定返回类型,那么在方法的最后一个字符和:之间需要一个空格,让我们指定返回类型

def unary_-: Rational = new Rational(-numer, denom)
scala> def test_-: Int = 1   // the method name is `test_-:`
<console>:1: error: '=' expected but identifier found.

scala> def test_- : Int = 1  // now the method name is `test_-`, and this is okay.
test_$minus: Int
我听到的理由是:也是标识符的合法部分,因此我们需要一种分离标识符和方法名称结尾的方法。但是字母也是标识符的合法部分,所以如果我们只有一个全是字母的方法名,为什么不需要一个空格呢

首先,标识符可以以字母开头 后面可以是任意字母和数字序列。这可能是 后跟下划线“\u1”字符和另一个由两个字母组成的字符串 和数字或运算符字符

也就是说,要将运算符字符包含到标识符中,它们必须用下划线连接

查看
def-unitary.-:Rational=new-Rational(-numer,denom)
,下划线将
unitary
-:
,如果没有空格,冒号将被解释为方法名称的一部分。因此,由于冒号是方法名称的一部分,它无法在返回类型之前找到冒号

def unary_-: Rational = new Rational(-numer, denom)
scala> def test_-: Int = 1   // the method name is `test_-:`
<console>:1: error: '=' expected but identifier found.

scala> def test_- : Int = 1  // now the method name is `test_-`, and this is okay.
test_$minus: Int
只有字母的方法名不会有这个问题,因为冒号不会被下划线后面的名称吸收