是否有 'strict' 模式来禁用 Kotlin 中的自动 'toString()' 调用?

Is there a 'strict' mode to disable the automatic 'toString()' calling in Kotlin?

我正在将一些非常严格的字符串类型 Java API 移植到 Kotlin 中。许多字符串具有不同的含义,我正在创建更有意义的类型。我以前在 Java 中做过这件事,而且我越来越讨厌自动 'toString'-ing 类型。 如此简单的例子:

fun someMethod(protocol: String, host: String) {
    val connectionString = "$protocol:$host"
}

protocol和host都可以用字符串来表示,但是本质上是不同的,所以具体介绍一下:

class Protocol(val definition:String)
class Host(val definition:String)

然后替换参数定义:

fun someMethod(protocol: Protocol, host: Host) {
    val connectionString = "$protocol:$host"
}

现在 connectionString 代码仍然假定这是两个可以连接的字符串。 编译器一点也不抱怨,因为它只是在这些类型上调用 toString(),这总是会产生某种字符串,但它很可能类似于 [Host@458ad742]

但我真的很想在这里看到某种类型的错误或警告。过去,我曾求助于从 toString 中抛出 RuntimeExceptions 来消除这些情况。这太野蛮了,对我来说,编译时错误比运行时错误好得多。

对我来说,强类型的美妙之处在于 运行。

所以:有人知道编译器标志/分析器/linter/IDE/在编译时找到这些的咒语吗?

无法关闭此功能,您必须覆盖 toString() 才能执行您想要的操作:

class Protocol(val definition:String) {
    override fun toString() = definition
}