考虑下面的例子,是否有可能为x
设置一个接受Int
的setter和另一个接受Double
?不同类型的属性设置器
class Test(x: Float) {
var x: Float = x
get() {
return field
}
set(value) { // 'value' is of type 'Float'
field = value
}
}
原因:如果我要指定一个新值x
我总是要在f
后缀追加到每一个任务,即
var v = Test(12f)
v.x = 11 // error: 'The integer literal does not conform to the expected type Float'
v.x = 11.0 // error: 'The floating-point literal does not conform to the expected type Float'
v.x = 11f // ok
这是一件好事,可以防止错误发生,调用者不会意识到该属性必须是浮动。你不应该改变任何代码,除了使用double而不是float。 –