我是Scala的全新品牌,但我在调试我的东西时遇到了麻烦。我正在阅读一本书中的“测试”,用Family
方法制作familySize()
课程。我的解决方案如下:
class Family(names:String*) {
def familySize():Int = {
args.length
}
}
val family1 = new Family("Mom", "Dad", "Sally", "Dick")
family1.familySize() is 4
然而,这会产生错误:
scala:8: error: value is is not a member of Int
family1.familySize() is 4
^
one error found
我的问题是,我不知道如何看待args.length
等于什么。我只是尝试family1.familySize()
,但是当我运行它时它不会返回任何内容。
答案 0 :(得分:2)
首先,您没有args
:
class Family(names: String*) {
def familySize(): Int = names.length
}
您有几个选择:
1)简单的等式运算符
val family1 = new Family("Mom", "Dad", "Sally", "Dick")
family1.familySize() == 4
2)在Scalaz中有一个类似于类型安全等式运算符的JavaScript:
val family1 = new Family("Mom", "Dad", "Sally", "Dick")
family1.familySize() === 4
如果操作数具有不同的类型
,则抛出异常3)不同的测试库如:Scalatest,Specs2或Scalacheck。例如,在带有必须匹配器的ScalaTest中:
family1.familySize must equal (4)
答案 1 :(得分:2)
args
不存在,它是names
:
class Family(names: String*) {
def familySize(): Int = names.length
}
val family1 = new Family("Mom", "Dad", "Sally", "Dick")
println(family1.familySize()) // will output 4
您还可以避免names.length
周围的大括号。