下面的代码适用于测试用例:
但无法重置
测试用例:
val robot = new Robot()
val name = robot.name
robot.reset()
val name2 = robot.name
name should not equal name2
源代码:
class Robot {
val chars = ('A' to 'Z' )
var name : String = {
var num = 100 + Random.nextInt(899)
var sb = new StringBuilder
for (i <- 1 to 2 ) {
sb.append(chars(scala.util.Random.nextInt(chars.length)))
}
sb.append(num)
sb.toString()
}
def reset() : String = new Robot().name
}
请帮助解决此问题
答案 0 :(得分:1)
尝试
class Robot {
var name : String = randomName()
def randomName() = {
val chars = ('A' to 'Z' )
var num = 100 + Random.nextInt(899)
var sb = new StringBuilder
for (i <- 1 to 2 ) {
sb.append(chars(scala.util.Random.nextInt(chars.length)))
}
sb.append(num)
sb.toString()
}
def reset(): String = {
name = randomName()
name
}
}
请注意,尽管name
被分配了方法var name : String = randomName()
,但在后续访问中如何保持不变:
val robot = new Robot()
robot.name // res0: String = RV417
robot.name // res1: String = RV417
robot.name // res2: String = RV417
这是因为var
的值是已记忆的,这意味着它在第一次初始化后会被缓存。但是,我们仍然可以通过强制这样的重新分配来更改var
的值
def reset(): String = {
name = randomName()
name
}
输出
val robot = new Robot()
robot.name // res0: String = OE770
robot.reset()
robot.name // res2: String = PI287