0

I want to have Kotlin class with constructor and get another class as parameter like this.

class LogHelper(cls : class) {

}

I had the same class in java and I didn't have any problem with it.

public LogHelper(Class cls) {
    LOG_TAG = cls.getSimpleName();
}
Ali shatergholi
  • 3,353
  • 1
  • 21
  • 27

1 Answers1

3

You can use constructor with java.lang.Class parameter:

class LogHelper(cls: Class<*>) {
    val LOG_TAG = cls.simpleName
}

or Kotlin's KClass:

class LogHelper(cls: KClass<*>) { ... }

* - Star Projection, used to indicate we have no information about a generic argument.

Kotlin does not allow raw generic types (e.g. Class), you always have to specify the type parameter (e.g. Class<*>, Class<Any>, Class<SomeClass>).

BigSt
  • 19,607
  • 4
  • 63
  • 81
  • Thanks for your answer. the right answer for my question was KClass and I find out because of your suggestion. Please add it in your answer. – Ali shatergholi Mar 10 '19 at 12:17
  • @Alishatergholi it may be worth mentioning that raw types are heavily discouraged even in Java. – Salem Mar 10 '19 at 12:27
  • @Moira do you have any link to explain when we should use raw type. – Ali shatergholi Mar 10 '19 at 12:35
  • 1
    @Alishatergholi if possible, [never](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). They are not type safe. – Salem Mar 10 '19 at 12:51