Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi! I'm trying to create a class that accepts a class parameter and its print function prints the name of provided class.


Kotlin
class A<T>(val t: T) {
    fun print() {
        println(t!!::class.java.simpleName)
    }
}

class B {}

fun main() {
   val b = B()
   A(b).print()
}


The output is
B


But in this scenario, I had to construct B first, and then pass it as a parameter.
I don't want this, I want my class to be modified to accept a class parameter instead so that I can run it like.
Kotlin
fun main() {
    A(B::class).print()
}


What I have tried:

I have tried to print the name of the class by passing that class inside another class and using class.java.simpleName property, I tried to print its name. But in my scenario, i always need to construct that class to pass that class in it. how can i achieve, what could be the syntax of my class so it will accept my class.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900