python vars()在Kotlin中
这个python代码
class Test: def __init__(self): self.one = "python" self.two = "is" self.three = "fun!" t=Test() print(vars(t))
打印一组字段和它们的值: {'one': 'python', 'two': 'is', 'three': 'fun!'}
我怎样才能在Kotlin中做同样的事情?
如果您正在使用Koltin数据类,则可以打印该类
class Test(val one: String, val two: String, val three: String) fun main(args: Array<String>) { val test = Test("Kotlin", "is", "fun") println(test) }
这将产生: Test(one=Kotlin, two=is, three=fun)
Kotlin数据类还提供了componentN()
函数。 在这里找一些关于Kotlin数据类的信息
对于普通班级,你可以尝试这个答案的方法