Tag: 构造函数

在kotlin中,如何使主构造函数的setter属性为private?

在kotlin中,如何使主构造函数的setter属性为private? class City(val id: String, var name: String, var description: String = “”) { fun update(name: String, description: String? = “”) { this.name = name this.description = description ?: this.description } } 我想让属性name的setter是私有的,而且它的getter是公开的,我该怎么办?

如何传递次kotlin构造函数variables?

我正在研究Kotlin gigasecond锻炼练习的解决方案: http ://exercism.io/exercises/kotlin/gigasecond/readme。 我可以理解它如何需要两个两个构造函数,因为在创建类时传入LocalDate和LocalDateTime参数。 我不明白的是如何将下面的次级构造函数variables传入并在类中使用。 看来只有当传入LocalDateTime参数时才会进行计算,因为只能使用dobWithTime进行计算。 这里发生了什么魔术? data class Gigasecond(val dobWithTime: LocalDateTime) { constructor(dateOfBirth: LocalDate) : this(dateOfBirth.atStartOfDay()) val date: LocalDateTime = dobWithTime.plusSeconds(1000000000) }

Kotlin:二级构造函数参数中的“val”是不允许的

我有以下课程: class Person(val name: String) { private var surname: String = “Unknown” constructor(name: String, surname: String) : this(name) { this.surname = surname } } 但是,当我想要在第二个构造函数中具有不变的名称参数时: constructor(val name: String, surname: String) : this(name) { this.surname = surname } 我有以下编译时错误: Kotlin:二级构造函数参数中的“val”是不允许的 有人可以解释为什么Kotlin编译器不允许这样做?

Kotlin构造函数:小学和中学

刚刚开始与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 = …) […]

Kotlin构造函数中的语句

有没有办法在Kotlin中混合语句(如打印语句)和成员分配? 这里是我想要做的一个例子(用Java): class MySystem { ComponentA componentA; ComponentB componentB; public MySystem() { System.out.println(“Initializing components”); this.componentA = new ComponentA(); System.out.println(“Constructed componentA”); this.componentB = new ComponentB(); System.out.println(“Constructed componentB”); } } 感谢任何输入,谢谢。