scala变量名参数
我正在尝试实现一个控制流结构,它可以接受数量可变的按名称参数 请参见CalculateGroup方法及其使用 我试图跟进,但仍有一些问题 从错误中可以看出,我怀疑我需要在CalculateGroup函数中定义一个类型注释谓词 以下是当前代码:scala变量名参数,scala,Scala,我正在尝试实现一个控制流结构,它可以接受数量可变的按名称参数 请参见CalculateGroup方法及其使用 我试图跟进,但仍有一些问题 从错误中可以看出,我怀疑我需要在CalculateGroup函数中定义一个类型注释谓词 以下是当前代码: def compare[T : Numeric](x: T)(y: T) : Boolean = implicitly[Numeric[T]].gt( x, y ) val items = compare[Double](10) _ val as
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:错误:'')应为“”,但找到“:”。
def CalculateGroup(列表:(谓词:=>布尔)*)=
^
/Users/pavel/Documents/ControlFlow/ControlFlow.scala:68:错误:')'应为“”,但找到“}”。
}
^
发现两个错误
你有语法问题。。。在方法
CalculateGroup
的签名和foreach
的谓词前面放置一个冒号。只要删除它们,它就会编译
只需删除它,就可以知道单词谓词
不是变量的别名,而是类的名称。所以如果你把它资本化就更好了。与你的方法相反,它不应该被资本化
更新
要具有多个按名称参数,只需执行以下操作:
def CalculateGroup( list: (=> Boolean) *) =
{
list.foreach( (p : (=> Boolean) ) => {
if (assertionsEnabled && !p)
throw new AssertionError
})
}
你有语法问题。。。在方法CalculateGroup
的签名和foreach
的谓词前面放置一个冒号。只要删除它们,它就会编译
只需删除它,就可以知道单词谓词
不是变量的别名,而是类的名称。所以如果你把它资本化就更好了。与你的方法相反,它不应该被资本化
更新
要具有多个按名称参数,只需执行以下操作:
def CalculateGroup( list: (=> Boolean) *) =
{
list.foreach( (p : (=> Boolean) ) => {
if (assertionsEnabled && !p)
throw new AssertionError
})
}
您不能按名称使用var args,您可以使用惰性集合,如迭代器
或流
:
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)
)}
您不能按名称使用var args,您可以使用惰性集合,如迭代器
或流
:
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)
)}
他试图拥有数量可变的按名称参数,这是不可能的。他试图拥有数量可变的按名称参数,这是不可能的。你的代码工作正常。然而,正如我在下一篇文章中看到的,这是可能的。谢谢哦我懂了。看起来这不受支持:。。认可的。谢谢您的代码运行良好。然而,正如我在下一篇文章中看到的,这是可能的。谢谢哦我懂了。看起来这不受支持:。。认可的。谢谢