簡體   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