简介
目标:在Scala方法中使用(多个)setter。
测试
test("testCity") {
val numberSequences = new NumberSequences()
numberSequences.test("utrecht")
assert("utrecht" === numberSequences.city)
}
代码
var _city: String = null
def city_=(_city:String) = this._city = _city
def city = this._city
def test(s: String) : String = {
city_=(s)
}
输出
错误表示存在类型匹配,这在测试中与numberSequences.city_=("utrecht")
一样奇怪。
> test
[info] Compiling 1 Scala source to C:\path\to\developme
nt\scalaNumberSequences\target\scala-2.10\classes...
[error] C:\path\to\development\scalaNumberSequences\src
\main\scala\com\utrecht\numbersequences\NumberSequences.scala:86: type mismatch;
[error] found : Unit
[error] required: String
[error] city_=(s)
[error] ^
[error] one error found
[error] (compile:compile) Compilation failed
[error] Total time: 1 s, completed Aug 10, 2014 8:53:37 PM
答案 0 :(得分:1)
def test(s: String) : String = {
city_=(s)
}
在这里设置var city_
的变量,但是你的方法签名说它应该返回一个String,函数的返回类型来自最后一行而赋值没有返回类型,要么返回一些字符串最后:
def test(s: String): String = {
city_=(s)
s
}
或者使它成为类似于setter的方法并返回单位:
def test(s: String): Unit = {
city_=(s)
}