How to rewrite Double

I am not sure if I am approaching this the right way. My goal is to define a variable to represent a number, such as
var speed: Double = 10 //Default units in m/s

When I use it, I want to be able to say println (speed) when I want the result in the default units of m/s, but println (speed.tokmh()) if I want it in km/h. It seems I have to make speed a class and write a function under it. But I am unsure how to make it produce a value in m/s when used like a variable without the function.

If you want your class to be printed as a double you can just override toString for that class.


You could create an extension function on Double to convert it to the proper string.

fun Double.tokmh() : String { ... }
1 Like