Johann
Johann

Reputation: 29867

Pass a reference to a class that is not instantiated

In Kotlin, I have a class and I would like to pass a reference of the class to a function that takes that reference as a parameter. The function will create an instance of the class. I am not sure how to define the function's parameter or how to pass a reference to the class. For example:

class User {
  var name: String = ""
}

fun processUser(userClass: User) {
  // Create an instance of User
  val user = userClass()
  user.name = "John Doe"
}

// Call the function. Something like this...
processUser(User.java)

I know that this could be done using KClass but was wondering if this could be done with the specific class that I want to instantiate, which in this case is User.

Upvotes: 0

Views: 71

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

What your processUser() function expects at the moment is an instance of User. What you actually want to receive is a function that creates a User. So it should be

fun processUser(userSupplier: () -> User) {
    // Create an instance of User
    val user = userSupplier()
    user.name = "John Doe"
}

fun main() {
    processUser { User() }
    // or simply via a constructor reference
    processUser(::User)
}

Upvotes: 2

Related Questions