1

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.

4

2 回答 2

3

以这种方式引用的构造函数就像任何其他函数引用一样。它有输入(参数)和返回值(类的新实例)。您可以将其传递给具有函数参数或某种工厂的高阶函数。

例如:

class MessageWrapper(val message: String)

val someStrings = listOf("Hello world")

您可以使用 lambda 将列表转换为具有这样的包装器类型:

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

但是通过直接传递构造函数跳过将函数包装在另一个函数中可能更清楚。

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

不过,与构造函数相比,函数和参数的清晰度改进更为明显。它还可以it通过避免嵌套 lambda 来帮助避免阴影 s。

于 2020-02-02T19:09:13.740 回答
1

对构造函数的引用是 Kotlin 反射 API 的一部分。您可以通过构造函数引用创建类的实例,即使该类甚至不在您的项目中(您从外部获取该引用)。反射被许多库和框架(例如,GSON)广泛使用,它们对您的代码一无所知,但仍然能够创建您的类的实例。

于 2020-02-02T18:30:18.357 回答