Primary Constructor and Initializer Blocks. The primary constructor has a syntax that is limited and cannot contain any code it. So to insert the initialization code an initializer block is used with init, example: Code : fun main(args: Array<String>) { val person1 = NAme("kotlin", 31) ...
In Kotlin, there are two constructors: Primary constructor - concise way to initialize a class Secondary constructor - allows you to put additional initialization logic Primary Constructor The primary constructor is part of the class header. Here's an example: class Person(val firstName: String, ...
In the below examples, we will create a triple by using the constructor.Example 1:fun main() { // creating a new instance of the Triple val(a, b, c) = Triple(10, 20, 30) // Printing the values println(a) println(b) println(c) } ...
classPerson(val name:String){constructor(name:String,age:Int):this(name){// 初始化...}} 如果一个非抽象类没有声明构造函数(主构造函数或次构造函数),它会产生一个没有参数的构造函数。构造函数是 public 。如果你不想你的类有公共的构造函数,你就得声明一个空的主构造函数: classDontCreateMeprivatecon...
classFoo @Inject constructor(dependency: MyDependency) { ... } 你也可以标注属性访问器 1 2 3 4 classFoo { varx: MyDependency? =null @Injectset } 构造函数 注解可以有接受参数的构造函数 1 2 3 annotationclassSpecial(val why: String) @Special...
1 . 如果父类有主构造函数 :其中的 constructor 如果没有注解与可见性操作符 , 可以省略 ; 代码语言:javascript 代码运行次数:0 运行 AI代码解释 openclassFatherconstructor(varname:String,varage:Int){open funaction(){println("Father")}} 2 . 子类有主构造函数 :子类需要在主构造函数中定义需要的变量 ,...
You can automatically define a property with a parameter of a primary constructor simply putting the keywords val or var in front of the parameter. In this example, the primary constructor of the first class defines properties, while the second does not. 代码语言:javascript 代码运行次数:0 运行...
constructor(name:String,parent:Person,age:Int):this(name,parent){ } } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 2.2 类的继承 在Kotlin中所有类都有一个共同的超类Any,对于没有超类型声明的类是默认超类,Any有三个方法:equals()、hashCode()和toString(),...
Kotlin | Constructor Overloading: Here, we are implementing a Kotlin program to demonstrate the example of constructor overloading. Submitted byIncludeHelp, on June 03, 2020 Constructor Overloading A Kotlin class has a primary constructor and one or more secondary constructors. When a class has...
Kotlin 的构造函数可以写在类头中,跟在类名后面,如果有注解还需要加上关键字constructor。这种写法声明的构造函数,我们称之为主构造函数。例如下面我们为Person创建带一个String类型参数的构造函数。 classPerson(privatevalname:String){funsayHello(){println("hello $name")}} ...