簡體   English   中英

不確定此Scala語法在做什么

[英]Not sure what this Scala Syntax is doing

我對Scala還是很陌生,我想知道以下代碼行在做什么:

class E{
  val (a: A, b: B, c:C, d:D) = {
    ...
  }
}

它是否正在執行賦值(由於val?)然后執行主體?

執行主體,然后破壞其結果

val (a: A, b: B, c:C, d:D) = {
    ...
}

首先,主體產生一些結果(預期為tuple *),然后將此元組分解成其元素,每個元素分別分配給abcd

您可能已經在Java中看到了以下代碼:

int x = 1, y = 2, z = 4;
// now x is 1, y is 2, z is 4

甚至是python中的以下代碼:

>>> x, y = 1, 2
>>> x
1
>>> y
2

Scala通過稱為destructuring Assignment的功能將它帶入了一個新的高度,雖然它不允許Java和Python語法,但它更加靈活,因為它不僅允許您獲得類似的體驗(通過使用元組):

val (x, y) = (1, 2)

但也有這種模式匹配用例的廣義和可擴展概念 ,例如在數組上:

val xs = Array(1,2,3,4)
val Array(first, second, _*) = xs  // _* mean I don't care about the rest of elements
// first: Int = 1
// second: Int = 2

在清單上:

val head::tail = List(1,2,3,4)
head: Int = 1
tail: List[Int] = List(2, 3, 4)

在許多其他情況下。

您可能會認為此操作會以某種方式破壞原始值,但通常不會(除非自定義提取器函數會產生副作用)

*元組是一個有點像有限已知大小的不可變集合,它的每個元素可以直接尋址其._x方法,像foo._1為第一個, foo._2為第二個。 Scala中的元組具有語法糖-大括號。

val定義了一個不能重新分配的變量。 然后, (a, b, ..)表示法公開了具有要分配的值a,b,...的元組。

這是您可以運行的示例:

// define types
type A = String
type B = String
type C = String
type D = String

// adding tuple@ to show a,b,c,d are components of a tuple aka extraction
val tuple@(a: A, b: B, c:C, d:D) = {
  ("aString", "bString", "cString", "dString")
}

println(tuple)

此外,您可以更明確地指定類型,例如

val tuple@(a: A, b: B, c:C, d:D): (A, B, C, D) = {
  ("aString": A, "bString": B, "cString": C, "dString": D)
}

輸出為:

defined type alias A
defined type alias B
defined type alias C
defined type alias D
tuple: (A, B, C, D) = (aString,bString,cString,dString)
a: A = aString
b: B = bString
c: C = cString
d: D = dString
(aString,bString,cString,dString)

您可以運行scala -Xprint:parser -e "val (a, b) = (1, 2)"對代碼進行解糖。 實際發生的是:

val x$1 = (1, 2) match {
  case Tuple2((a @ _), (b @ _)) => Tuple2(a, b)
}
val a = x$1._1
val b = x$1._2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM