What is the purpose of constructor references in Kotlin

1.7k views Asked by At

I am reading the book Kotlin in action and I ask myself what is the purpose of "creating an instance of a class using a constructor reference" (page 112 if anyone is interested and has the book at home).

Here is the code example from the book:

data class Person(val name: String, val age: Int)

val createPerson = ::Person
val p = createPerson("Alice", 29)

println(p) // Person(name=Alice, age=29)

I think it looks like an factory method call, but I dont think that this is the (only) purpose of the method reference here.

2

There are 2 answers

0
ardenit On

References to constructors are the part of Kotlin Reflection API. You can create an instance of a class through constructor reference even if that class is not even in your project (you get that reference from outside). Reflection is widely used by many libraries and frameworks (for example, GSON) that know nothing about your code but still are able to create instances of your classes.

5
Tenfour04 On

A constructor when referenced this way is just like any other function reference. It has inputs (the parameters) and a return value (a new instance of the class). You can pass it to a higher-order function that has a function parameter or some kind of factory.

For example:

class MessageWrapper(val message: String)

val someStrings = listOf("Hello world")

You could convert your list to have the wrapper type like this by using a lambda:

val someMessages: List<MessageWrapper> = someStrings.map { MessageWrapper(it) }

but it is possibly clearer to skip wrapping your function in another function by passing the constructor directly.

val someMessages: List<MessageWrapper> = someStrings.map(::MessageWrapper)

The improvement in clarity is more apparent with functions and parameters than it is with constructors, though. It also can help avoid shadowed its by avoiding nested lambdas.