-2

I want to make an extension function(named (printDatatype) for example) that can be applied on all datatypes and just prints it ... for example :

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

  56.prinDatatype()==>output: 56

  null.printDatatype()==>output: null

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

2 Answers2

0

Soo something like this?

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

Any custom objects will need to override the toString method (like always). That will be auto on data classes.

I honestly don't know what the use case for something like would be.

AlexT
  • 2,524
  • 1
  • 11
  • 23
-2

so i figured it out :)

fun Any?.printMe() {
        if (this is Class<*>) {
            println(this.toString())
        } else if (this.toString() == "null"){
            println("null")
        }
        else {
            println(this)
        }
    }
  • And that differs from a simple `println(this)` how, exactly?  (If you trace it through `println()` ends up by printing "null" for a null object, else the results of calling `toString()` on it (via `String.valueOf()`).) – gidds Mar 19 '21 at 17:59
  • The other answer would effectively convert it to an extension function. `println()` already does what you described as your assignment, so your first two branches of code are just extra convolution. I'm afraid either you have misunderstood your assignment, or the teacher has given you a nonsensical assignment, because there is no version of the `println()` function that doesn't already do what your first two branches are doing. – Tenfour04 Mar 19 '21 at 18:29