Scala 点语法(或缺少语法)

编程入门 行业动态 更新时间:2024-10-10 23:20:59
本文介绍了Scala 点语法(或缺少语法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在阅读精彩的书在 Scala 中编程遇到一段对我来说毫无意义的代码:

I was going through the wonderful book Programming in Scala when I came across a piece of code that just doesn't make sense to me:

def above(that: Element): Element = { val this1 = this widen that.width val that1 = that widen this.width elem(this1.contents ++ that1.contents) }

注意第 2 行和第 3 行:

Note line 2 and 3:

val this1 = this widen that.width

看来我应该可以用:

val this1 = this.widen that.width

但是,当我尝试编译此更改时,会出现以下错误:

However, when I try to compile this change, it gives the following error:

错误:';'预期但'.'成立.val this1 = this.widen that.width^

error: ';' expected but '.' found. val this1 = this.widen that.width ^

为什么这种语法不可接受?

Why is this syntax unacceptable?

推荐答案

第 2 行将方法 widen 用作操作符,而不是将其用作 Java 方式中的方法:

Line 2 uses the method widen as an operator, instead of using it as a method in the Java way:

val this1 = this.widen(that.width)

发生错误是因为您省略了括号,只有在使用运算符表示法的方法时才能这样做.您不能这样做,例如:

The error occurs because you've left out the parentheses, which you can only do when you use a method in operator notation. You can't do this for example:

"a".+ "b" // error: ';' expected but string literal found.

你应该写

"a".+ ("b")

实际上你可以用整数来做到这一点,但这超出了这个问题的范围.

Actually you can do this with integers, but that's beyond the scope of this question.

阅读更多:

  • 您的书的第 5 章第 3 节是关于运算符表示法的,至少在第一版第 5 版中是这样的
  • Scala 之旅:运算符

更多推荐

Scala 点语法(或缺少语法)

本文发布于:2023-11-25 14:57:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630204.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!