理解Scala符号语法

理解Scala符号语法,scala,Scala,我有以下代码: 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 Excep

我有以下代码:

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
我想知道最后一行是如何工作的。没有从Int到SimpleList的隐式转换。因此,我不理解方法调用机制

Object.method(Arg)


我在这里看不到这种模式。我认为对Scala符号(中缀、后缀、后缀等)的澄清会有所帮助。我想理解语法糖。

是正确的操作数方法。在scala中,如果方法名以冒号结尾,则在右操作数上调用该方法。 所以
1::2::Empty
实际上是
空的。:(2)
它返回一个
SimpleList


一旦您了解到
::
是正确操作数的方法,后续的
1::
就很容易理解。

在Scala中,方法名称以冒号结尾

  • 窗体右关联表达式
  • 在右操作数上额外调用

所以
1::2::Empty
实际上是
空的。::(2)。:(1)

这应该是公认的答案。如果没有正确的关联性,仅对正确的操作数调用方法是不够的。