【发布时间】:2012-07-22 03:04:00
【问题描述】:
我想在 Scala 中编写一个类,它可以像这样使用任意数量的字节或布尔值
class Bytes(data: Byte*) {
def this(data: Boolean*) = this {
val res: Array[Byte] = convBools2Bytes(data)
res: _*
}
// […]
}
其中convBools2Bytes 是将Array[Boolean] 转换为Array[Byte] 的函数:
def convBools2Bytes(data: Array[Boolean]): Array[Byte]
这给了我以下编译器错误:
[error] Bytes.scala:5: no `: _*' annotation allowed here
[error] (such annotations are only allowed in arguments to *-parameters)
[error] res: _*
[error] ^
据我了解,res: _* 语句将Array[Byte] 转换为重复参数列表(如“Programming in Scala”, 2nd Ed. 中的第 8.8 节所述)。
为什么会出现这样的错误,我该如何避免?
【问题讨论】:
-
我刚刚插入了
convBools2Bytes来说明问题。没有考虑。在实际实现中,这个块中有很多代码。所以在这个例子中它真的没有任何意义。
标签: scala constructor variadic-functions