如何制作在kotlin中打印所有数据类型的扩展函数?

问题描述

我想制作一个可以应用于所有数据类型的扩展函数(例如命名(printDatatype)),并且只打印它......例如:

 "example".printDatatype() ==>output: example

  56.prinDatatype()==>output: 56

  null.printDatatype()==>output: null

  className.printDatatype()==> output: ClassName(property1 = value,property2 = value ....)

解决方法

是这样的吗?

fun Any?.printLn() = println(this)

任何自定义对象都需要覆盖 toString 方法(一如既往)。这将是数据类的自动。

老实说,我不知道类似的用例是什么。

,

所以我想通了:)

fun Any?.printMe() {
        if (this is Class<*>) {
            println(this.toString())
        } else if (this.toString() == "null"){
            println("null")
        }
        else {
            println(this)
        }
    }