繁体   English   中英

理解 Scala Notation 语法

[英]Understanding Scala Notation syntax

我有以下代码:

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 的隐式转换。 因此我不了解方法调用机制。

对象.方法(Arg)

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

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

  • 形成右结合表达式
  • 另外在正确的操作数上调用。

所以1 :: 2 :: Empty实际上是Empty.::(2).::(1) .

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

一旦您理解::是正确操作数的方法,后续的1 :: <the-new-simple-list>很容易理解。

暂无
暂无

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

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