2016-04-08 51 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

他试图使用可变数量的名称参数,这是不可能的 –