[英]Understanding Scala Notation syntax
I have the following code:我有以下代码:
abstract class AList {
def head:Int
def tail:AList
def isEmpty:Boolean
def ::(n: Int): AList = SimpleList(n, Empty)
}
object Empty extends AList {
def head = throw new Exception("Undefined")
def tail = throw new Exception("Undefined")
def isEmpty = true
}
case class SimpleList(head: Int, tail: AList = Empty) extends AList {
def isEmpty = false
}
1 :: 2 :: Empty
I wonder how the last line actually works.我想知道最后一行实际上是如何工作的。 There is no implicit conversion from Int to SimpleList.
没有从 Int 到 SimpleList 的隐式转换。 Hence I do not understand the method call mechanism.
因此我不了解方法调用机制。
Object.method(Arg)
对象.方法(Arg)
I do not see that pattern here.我在这里看不到这种模式。 I think a clarification of Scala notation (infix, suffix, postfix, etc...) would help.
我认为澄清 Scala 符号(中缀、后缀、后缀等)会有所帮助。 I'd like to understand the syntactic sugar.
我想了解语法糖。
In Scala, method names ending with a colon..在 Scala 中,方法名以冒号结尾..
So 1 :: 2 :: Empty
is actually Empty.::(2).::(1)
.所以
1 :: 2 :: Empty
实际上是Empty.::(2).::(1)
。 . .
::
is a method of the right operand. ::
是正确操作数的方法。 In scala if a method name ends in a colon the method is invoked on the right operand.在 scala 中,如果方法名称以冒号结尾,则在右操作数上调用该方法。 So
1 :: 2 :: Empty
is actually Empty.::(2)
which returns a SimpleList
.所以
1 :: 2 :: Empty
实际上是Empty.::(2)
,它返回一个SimpleList
。
The subsequent 1 :: <the-new-simple-list>
is easy to follow once you understand that ::
is a method of the right operand.一旦您理解
::
是正确操作数的方法,后续的1 :: <the-new-simple-list>
很容易理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.