class Person(private val username: String, private var age: Int){} 1. Secondary Constructor定义在类中,可以有多个,Primary Constructor只能有一个 class MyButton : AppCompatButton { constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context...
在构造对象过程中,有三个地方可以对成员进行初始化:1)是在首构造方法(Primary constructor);2)是在声明成员的同时进行初始化,或者是在**初始化代码块(init {...})中;3)是在次要构造方法(Secondary constructor)**中。 要注意它们之间的区别和执行顺序,首构造方法是最先执行的,但它不能运行代码,只能进行赋值;...
正如上面注释所写到的,Kotlin 中的类可以有一个 主构造器 (primary constructor), 以及一个或多个 次构造器 (secondary constructor). 主构造器是类头部的一部分, 位于类名称(以及可选的类型参数)之后,并且有一点与Java不同,就是在主构造器中我们可以直接声明成员属性。 当然还有点不同的是,kotlin为我们提供了一...
The most common usage of secondary constructors comes in subclasses when you need to initialize the class in different ways. If the class contains a primary constructor, the secondary constructor must refer to it in its declaration. The declaration is done usingthiskeyword. class Student(var name...
classDataClassWithSecondaryConstructors(valname: String,valsurname: String,valage: Number ) {constructor() :this("","Doe",Int.MIN_VALUE)constructor(name: String) :this(name,"Deere",Int.MIN_VALUE)constructor(name: String, surname: String) :this(name, surname,Int.MIN_VALUE) } ...
在Kotlin 中,data class 已经默认生成了一个默认的构造函数,如果需要自定义构造函数,可以这样做: dataclassUser(valname:String,valage:Int){// 自定义构造函数constructor(name:String):this(name,0)} 1. 2. 3. 4. 在上述代码中,我们定义了一个接收name参数的构造函数,并在其中调用了默认的构造函数。
3. Adding an Empty Secondary Constructor We’ve known that a Kotlin data class’s primary constructor must have at least one argument. Let’s see an example: dataclassArticleWithoutDefault(vartitle: String,varauthor: String,varabstract: String,varwords:Long) ...
如果想为 Point 类添加默认构造函数, 则需要添加辅助构造函数 (secondary constructor): data class Point(val x: Double, val y: Double) { constructor() : this(0.0, 0.0) } 1 2 3 如果不想这么麻烦, 最好的办法是给主构造函数的参数添加默认值: data class Point(val x: Double = 0.0, val y: ...
class World这样我们就声明了一个World类。7.2.2 构造函数在Kotlin 中,一个类可以有一个主构造函数(primary constructor)和一个或多个 次构造函数(secondary constructor)。主构造函数主构造函数是类头的一部分,直接放在类名后面:open class Student constructor(var name: String, var age: Int) : Any() { ....
class AuthLog: Log { constructor(data: String): this(data, 10) { // code } constructor(data: String, numberOfData: Int): super(data, numberOfData) { // code } } Example: Kotlin Secondary Constructor funmain(args:Array<String>){valp1 = AuthLog("Bad Password") }openclassLog{vardata...