我在Kotlin代码中经常使用类型别名,但我想知道是否可以对它们强制类型安全.
typealias Latitude = Double
typealias Longitude = Double
fun someFun(lat: Latitude, lon: Longitude) {...}
val lat: Latitude = 12.34
val lon: Longitude = 56.78
someFun(lon, lat) // parameters are in a wrong order, but the code compiles fine
如果我能以某种方式防止类型别名之间的隐式强制转换,从而帮助避免此类问题,那就太好了.
当然,存在一个问题,即对基本类型的操作对TypeAlias不可用,但可以通过扩展函数(或强制转换)来解决.
I don't want to use data classes, holding a single field, because it seems a bit of overkill, especially for primitive types (or maybe I am wrong and they'll be optimized out?)
So the question: can I somehow enforce type-safety for typealiases?