简体   繁体   English

为什么“val a = -1”在scala中不起作用?

[英]Why “val a=-1” doesn't work in scala?

I found val a = -1 works well in scala REPL, but if I skip the space around the = like val a=-1 , the expression doesn't return the result. 我发现val a = -1在scala REPL中运行良好,但如果我跳过= val a=-1周围的空格,则表达式不会返回结果。

Does anyone have ideas about this? 有没有人有这个想法? Why the space arount the = is necessary here? 为什么arount的空间=是必要的吗?

=- is a legitimate method name in Scala; =-是Scala中合法的方法名称; the following will work: 以下将有效:

class A {
  def =-(i: Int) = i
}
val a = new A
a=-1

So the parser can't distinguish your val a=-1 from this case. 所以解析器无法区分你的val a=-1和这种情况。

val is used in 2 cases: val用于2种情况:

1) value declaration: 1)价值声明:

val a = 2
> a: Int = 2

2) pattern definition: 2)模式定义:

val Some(x) = Some(2)
> x: Int = 2

when you write val a=-1 , it clearly fails to match the "value declaration" syntax, so the compiler attempts "pattern definition" syntax. 当你写val a=-1 ,它显然无法匹配“值声明”语法,因此编译器尝试“模式定义”语法。

To see this is the case, let's put a semi-colon in the end of the line. 为了看到这种情况,让我们在行尾添加一个分号。

 val a=-1 ;
 > <console>:1: error: '=' expected but ';' found.

Indeed, the compiler is looking for the right hand side of pattern definition. 实际上,编译器正在寻找模式定义的右侧。

Now notice that =- is a valid identifier name. 现在请注意=-是一个有效的标识符名称。 So if it is a case class (or a normal class with unapply method), it can be used in pattern match syntax. 因此,如果它是一个case类(或带有unapply方法的普通类),它可以用在模式匹配语法中。

Let's see if this actually works: 让我们看看这是否真的有效:

case class =- (i: Int, j: Int)
> defined class $eq$minus

val a =- b = =-(2, 3)  // infix syntax for pattern match
> a: Int = 2
  b: Int = 3

// Yes. it works!

// This is same as:
val =-(a, b) = =-(2, 3) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM