2017-03-05 115 views
1

考虑下面的例子,是否有可能为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 
+0

这是一件好事,可以防止错误发生,调用者不会意识到该属性必须是浮动。你不应该改变任何代码,除了使用double而不是float。 –

回答

-1

什么:

class Test(x: Float) { 
    var x: Float = x 
     get() { 
      return field 
     } 
     set(value) { // 'value' is of type 'Float' 
      field = value 
     } 

    fun setX(value: Int) { 
     x = value.toFloat() 
    } 
} 
1

虽然你不能超载setter你可以利用Number接口的优势,只需接受所有数字并将它们转换为浮点数:

class Test(x: Float) { 
    var x: Number = x 
     get() { 
      return field 
     } 
     set(value) { // 'value' is of type 'Number' 
      field = value.toFloat() 
     } 
} 

这意味着,不仅FloatIntDouble被接受,但也ByteShortBigIntegerBigDecimalAtomicIntegerAtomicLongAtomicDouble,并实现Number任何其他类。