2016-04-08 36 views
0

我想實現一個控制流結構,它可以接受可變數目的名稱參數。斯卡拉可變數量按名稱參數

請參閱CalculateGroup方法及其用法。

我試圖按照this post,但仍然有一些問題

,我可以從錯誤中看到的,我懷疑我需要定義CalculateGroup功能類型註釋謂詞?

下面是當前的代碼:

def compare[T : Numeric](x: T)(y: T) : Boolean = implicitly[Numeric[T]].gt(x, y) 

val items = compare[Double](10) _ 

val assertionsEnabled = true 

def Calculate(predicate: => Boolean) = 
    if (assertionsEnabled && !predicate) 
     throw new AssertionError 

Calculate{ 
    items(5) 
} 

    def CalculateGroup(list: (predicate: => Boolean) *) = 
    { 
    list.foreach((p : (predicate: => Boolean)) => { 
     if (assertionsEnabled && !predicate) 
     throw new AssertionError 
    }) 
    } 

    CalculateGroup{ 
    items(5), 
    items(3), 
    items(8) 
    } 

錯誤的詳細信息:

scala ControlFlow.scala /Users/pavel/Documents/ControlFlow/ControlFlow.scala:36: error: ')' expected but ':' found. def CalculateGroup(list: (predicate: => Boolean) *) = ^ /Users/pavel/Documents/ControlFlow/ControlFlow.scala:68: error: ')' expected but '}' found. } ^ two errors found

回答

1

不能使用按名稱變參,你可以使用一個懶惰的集合像Iterator也許Stream

def compare[T : Numeric](x: T)(y: T) : Boolean = implicitly[Numeric[T]].gt(x, y) 

    val items = compare[Double](10) _ 

    val assertionsEnabled = true 

    def Calculate(predicate: => Boolean) = 
    if (assertionsEnabled && !predicate) 
     throw new AssertionError 

    Calculate{ 
    items(5) 
    } 

    def CalculateGroup(list: Iterator[Boolean]) = 
    { 
    list.foreach { (p : Boolean) => 
     if (assertionsEnabled && !p) { 
     throw new AssertionError 
     } 
    } 
    } 

    CalculateGroup{Iterator(
    items(5), 
    items(3), 
    items(8) 
)} 
+0

你的代碼工作正常。然而,正如我可以從下一篇文章中看到的那樣。謝謝。 http://stackoverflow.com/questions/13307418/scala-variable-argument-list-with-call-by-name-possible – Pavel

+0

哦..我明白了。看起來不支持:https://issues.scala-lang.org/browse/SI-5787 ..接受。謝謝! – Pavel

1

你有語法問題...您在的簽名放置一個冒號的話predicate前方法CalculateGroupforeach。只要刪除它們,它應該編譯。

只是刪除它,並知道單詞predicate不是變量的別名,但它應該是一個類的名稱。所以,如果你利用它,那會更好。與您的方法相反,不應將其大寫。

更新

有多個通過名稱參數只是這樣做:

def CalculateGroup(list: (=> Boolean) *) = 
{ 
list.foreach((p : (=> Boolean)) => { 
    if (assertionsEnabled && !p) 
    throw new AssertionError 
}) 
} 
+0

他試圖使用可變數量的名稱參數,這是不可能的 –