我有以下方法:
fun RowVector(x: Double, y: Double): RowVector2 = RowVector(listOf(x, y)) as RowVector2
fun RowVector(x: Double, y: Double, z: Double): RowVector3 = RowVector(listOf(x, y, z)) as RowVector3
fun RowVector(vararg elements: Double): RowVector = RowVector(elements.asList())
fun RowVector(elements: List<Double>): RowVector = // Actually creates the RowVector instance
虽然有一些合法的用例可以调用RowVector(elements: List<Double>)
,但我还是鼓励调用者使用vararg
版本的方法,因为这允许编译器进行一些更智能的类型推断,如下所示:
val vector1 = RowVector(listOf(0.0, 1.0, 2.0)) // Type is inferred to be RowVector
val vector2 = RowVector(0.0, 1.0, 2.0) // Compiler can see that only 3 values are passed and therefore infers RowVector3
因此,我在RowVector(elements: List<Double>)
中添加了@Deprecated
注释,它建议调用者使用vararg
版本,但如果用例实际上是合法的,则可以很容易地将其取消.
我面临的问题是@Deprecated
注释的ReplaceWith
部分的设计.我希望IDE将RowVector(listOf(0.0, 1.0, 2.0))
替换为RowVector(0.0, 1.0, 2.0)
,但到目前为止,我还没有找到这样做的方法:
@Deprecated(
"Prefer the vararg interface if possible as it allows the compiler to infer types better.",
ReplaceWith("RowVector(*elements.toDoubleArray())")
)
通向RowVector(*listOf(0.0, 1.0, 2.0).toDoubleArray())
,但仍需要手动清理.
@Deprecated(
"Prefer the vararg interface if possible as it allows the compiler to infer types better.",
ReplaceWith("RowVector(*doubleArrayOf(elements))")
)
奇怪的是什么都不做,而且
@Deprecated(
"Prefer the vararg interface if possible as it allows the compiler to infer types better.",
ReplaceWith("RowVector(*elements)")
)
字面上的替换是这样的:RowVector(*listOf(0.0, 1.0, 2.0))
.
我知道这是一个第一世界的问题,打电话的人可以很容易地阅读警告并删除listOf()
,但我还是会尽可能让打电话的人容易.