I'm porting some very stringly typed Java API into Kotlin. Lot's of strings have different meanings, and I'm in the process of creating more meaningful types. I've done that before in Java, and I've grown to profoundly hate the automatic 'toString'-ing of types. So simple example:
fun someMethod(protocol: String, host: String) {
val connectionString = "$protocol:$host"
}
Protocol and host can be represented as a string, but are fundamentally different, so I introduce specific types:
class Protocol(val definition:String)
class Host(val definition:String)
and then replace the parameter definitions:
fun someMethod(protocol: Protocol, host: Host) {
val connectionString = "$protocol:$host"
}
Now the connectionString code still assumes that these are two strings that can be concatenated. The compiler doesn't complain a bit, because it simply calls toString() on those types, and that will always result in some kind of string, but it very well might be something like [Host@458ad742]
But I would really like some kind of type error or warning here. In the past I've resorted to throwing RuntimeExceptions from the toString to smoke out these situations. That's pretty barbaric, and for me a compile time error is so much better than a runtime error.
For me the beauty of strong types is knowing these issues before running.
So: Does anyone know of a compiler flag / analyser / linter / IDE / incantation to find these at compile time?
There is no way to turn this off, you will have to override toString()
to do what you want:
class Protocol(val definition:String) {
override fun toString() = definition
}