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(); } 
4

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@Alishatergholi it may be worth mentioning that raw types are heavily discouraged even in Java.
@Moira do you have any link to explain when we should use raw type.
@Alishatergholi if possible, never. They are not type safe.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.