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();
}
Yoshimitsu
  • 4,343
  • 2
  • 22
  • 28
  • Class names typically start with a capital letter. – Eugen Pechanec Mar 10 '19 at 12:01
  • @EugenPechanec in java you right, but not in Kotlin – Yoshimitsu Mar 10 '19 at 12:04
  • 2
    `class` is a [keyword](https://kotlinlang.org/docs/reference/keyword-reference.html), [`Class`](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) is a Java class. [Class names typically start with a capital letter even in Kotlin.](https://kotlinlang.org/docs/reference/coding-conventions.html#naming-rules) – Eugen Pechanec Mar 10 '19 at 12:09
  • @EugenPechanec you right, I find Answer. – Yoshimitsu Mar 10 '19 at 12:15

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>).

Sergio
  • 27,326
  • 8
  • 128
  • 149
  • 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. – Yoshimitsu 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. – Yoshimitsu 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