class - Kotlin 中的调用构造函数引用

标签 class constructor reference kotlin

如果我有一个像这样的 kotlin 类:

data class  Anim (val name : String , var age : Int) {

constructor (a:Anim):this(a.name, a.age) {
}

constructor () :this("Dog") {  }

}

我想使用构造函数引用语法,

val a = ::Anim 

然后我得到了这个错误:

overload resolution ambiguity: 
public constructor PornModel() defined in com.ripple.PornModel
public constructor PornModel(a: PornModel) defined in com.ripple.PornModel
public constructor PornModel(name: String, country: String = ...) 
defined in com.ripple.PornModel
    val a = ::PornModel::( String,  String))

请告诉我这些论点有多特别

非常感谢任何帮助!铝

最佳答案

如错误消息中所述,Kotlin 编译器不知道要选择哪个构造函数重载。您已明确声明 a 的类型,例如:

val twoArgs: (String, Int) -> Anim = ::Anim
val oneArg: (Anim) -> Anim = ::Anim
val noArg: () -> Anim = ::Anim

关于class - Kotlin 中的调用构造函数引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47935596/

相关文章:

rust - 为什么不能在同一结构中存储值和对该值的引用?

c# - 我将如何为我的类实现 IDisposable 以便它可以在 'using' block 中使用?

arrays - 我不明白这个 Perl 语法,有人知道吗?

java - 如何从jar文件运行类文件,其中类文件位于bin文件夹中

java: 新文件 ("", "name") != 新文件 ("name") ? (带空字符串的文件构造函数)

node.js - TypeError : BrowserWindow is not a constructor

constructor - 使用构造函数参数列表而不是参数本身调用 Java new(在 Clojure 中)

javascript - 是什么原因导致这个: Uncaught TypeError: $ is not a function?

c++ - 使用单独编译时返回 typedef 类型

Python:提取特定列数据并将其存储到变量中