我可以在 Scala 中省略哪些字符? [英] Which characters can I omit in Scala?

查看:42
本文介绍了我可以在 Scala 中省略哪些字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,为什么我可以在下面的 T m 0(而不是 T.m(0))中省略点和刹车?

In Scala, why can I omit the dot and brakets in T m 0 (instead of T.m(0)) in the following?

scala> object T { def m(i:Int) = 0 == i }
defined module T

scala> T m 0
res19: Boolean = true

但是为什么我不能在下面的 n(0) 中省略刹车?

But why can't I omit the brakets in n(0) in the following?

scala> def n(i:Int) = 0 == i
n: (Int)Boolean

scala> n 0
<console>:1: error: ';' expected but integer literal found.
       n 0
         ^

推荐答案

前一个例子,T m 0,是一个运算符符号"的例子.Scala 有三种类型的运算符符号,前缀(称为一元)、中缀和后缀.让我们在此处查看所有三个实例的示例:

The former example, T m 0, is an example of "operator notation". Scala has three types of operator notations, prefix (called unary), infix and postfix. Let's see examples of all three in action here:

class MyByte(val n : Int) {
  require(n >= 0 && n <= 255)
  def unary_! = new MyByte(n ^ 0xff)
  def +(m : MyByte) = new MyByte(n + m.n)
  def bits = (math.log(n) / math.log(2) + 1).toInt
  override def toString = "0" * (8 - bits) + n.toBinaryString
}

这里正在使用:

scala> val a = new MyByte(5)
a: MyByte = 00000101

scala> val b = new MyByte(10)
b: MyByte = 00001010

scala> ! a  // Prefix/Unary
res58: MyByte = 11111010

scala> a + b  // Infix
res59: MyByte = 00001111

scala> b bits  // Postfix
res60: Int = 4

虽然中缀和后缀表示法接受任何有效的 Scala 标识符,尽管有人谈论限制后缀表示法,但只有四个标识符可以用作前缀:~、!、- 和 +.

While infix and postfix notations accept any valid Scala identifier, though there is talk of restricting postfix notation, only four identifiers can be used as prefix: ~, !, - and +.

现在,当您尝试 "m 0" 时,Scala 将其丢弃为一元运算符,理由是它不是有效运算符(~、!、- 和 +).它发现m"是一个有效的对象——它是一个函数,而不是一个方法,所有的函数都是对象.

Now, when you try "m 0", Scala discards it being a unary operator, on the grounds of not being a valid one (~, !, - and +). It finds that "m" is a valid object -- it is a function, not a method, and all functions are objects.

由于0"不是有效的 Scala 标识符,它既不能是中缀也不能是后缀运算符.因此,Scala 抱怨它期望;"-- 这将分隔两个(几乎)有效的表达式:m"和0".如果你插入它,那么它会抱怨 m 需要一个参数,或者,如果失败,一个_"将它变成一个部分应用的函数.

As "0" is not a valid Scala identifier, it cannot be neither an infix nor a postfix operator. Therefore, Scala complains that it expected ";" -- which would separate two (almost) valid expressions: "m" and "0". If you inserted it, then it would complain that m requires either an argument, or, failing that, a "_" to turn it into a partially applied function.

这篇关于我可以在 Scala 中省略哪些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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