enum class SubscriptionResultReason {
Success, InsufficientFunds, IncompatibleAccount
}
class SubscriptionResult(
val result: Boolean,
val reason: SubscriptionResultReason,
val description: String
)
fun main() {
val result = SubscriptionResult(
false,
IncompatibleAccount,
"Users account does not support this type of subscription"
)
// 输出结果为 'org.example.SubscriptionResult@13221655'
println(result)
}
调试器中显示的信息也没什么意义:
添加一个简单的 toString 实现, 对这两种情况可以显著的改善输出:
// 输出结果为 'Subscription failed (reason=IncompatibleAccount, description="Users
// account does not support this type of subscription")'
override fun toString(): String {
val resultText = if(result) "succeeded" else "failed"
return "Subscription $resultText (reason=$reason, description=\"$description\")"
}
class Person(
val name: String?,
val age: Int?,
val children: List<Person>
) {
override fun toString(): String =
"Person(name=$name, age=$age, children=$children)"
}
class PersonBuilder {
var name: String? = null
var age: Int? = null
val children = arrayListOf<Person>()
fun child(personBuilder: PersonBuilder.() -> Unit = {}) {
children.add(person(personBuilder))
}
fun build(): Person = Person(name, age, children)
}
fun person(personBuilder: PersonBuilder.() -> Unit = {}): Person =
PersonBuilder().apply(personBuilder).build()
你使用这个类型的方式如下:
如果你在上图显示的断点处暂停代码, 那么显示的信息没什么用处:
添加一个简单的 toString 实现, 可以产生更加有用的输出:
override fun toString(): String =
"PersonBuilder(name=$name, age=$age, children=$children)"