英文:
Kotlin secondary constructor never used
问题
我只会返回代码的翻译部分,不会回答关于翻译的问题。
我只会返回代码的翻译部分,不会回答关于翻译的问题。
```kotlin
我只是在学习Kotlin,这是我的代码
fun main() {
var Vinay = Person(lastName = "Vinay")
Vinay.hobby = "打网球"
Vinay.stateHobby()
Vinay.age = 25
println("Vinay 今年 ${Vinay.age} 岁")
}
class Person(firstName: String = "Chaitra", lastName: String = "Nadig") {
var age: Int? = null
var hobby: String = "编程"
init {
println("欢迎 $firstName $lastName")
}
constructor(firstName: String, lastName: String, age: Int)
: this(firstName, lastName) {
this.age = age
println("在构造函数内部") // 不会被打印
println("这个人是 $firstName $lastName,年龄是 $age 岁") // 不会被打印
}
fun stateHobby() {
println("爱好是 $hobby")
}
}
构造函数内部没有被打印,它说构造函数从未被调用。请检查你的代码以确保构造函数被正确调用。
英文:
I am just learning Kotlin and this is my code
fun main() {
var Vinay = Person(lastName = "Vinay")
Vinay.hobby = "Play tennis"
Vinay.stateHobby()
Vinay.age = 25
println(" vinay is ${Vinay.age} years old")
}
class Person(firstName: String = "Chaitra", lastName: String = "Nadig") {
var age: Int? = null
var hobby: String = "Coding"
init {
println("Welcome $firstName $lastName")
}
constructor(firstName: String, lastName: String, age: Int)
: this(firstName, lastName){
this.age = age
println("Inside the constructor"). //not getting printed
println("Person is $firstName $lastName aged $age") //not getting printed
}
fun stateHobby() {
println("Hobby is $hobby")
}
}
Nthing inside the construtor is getting printed. It says constructor never called. Kindly help
答案1
得分: 2
你的代码中有一个小问题:
fun main() {
var Vinay = Person("Vinay", "dave", 10)
Vinay.hobby = "打网球"
Vinay.stateHobby()
Vinay.age = 25
println("Vinay 今年 ${Vinay.age} 岁了")
}
复制并粘贴这段代码到你的函数中,它将会正常工作。你只是在创建对象时忘记调用了3个参数。构造函数的调用始终基于参数。
英文:
There is a minor issue in your code
fun main(){
var Vinay=Person("Vinay", "dave", 10)
Vinay.hobby="Play tennis"
Vinay.stateHobby()
Vinay.age=25
println(" vinay is ${Vinay.age} years old")
}```
Copy and paste in your function it will work, you just forgot to call 3 params while creating an object. constructor calling is always based on params
</details>
# 答案2
**得分**: 0
我通过评论找到了答案。构造函数接受的参数来自我们创建的实例。我之前在实例中只指定了一个参数,而我的构造函数需要3个参数。在我更改了实例后,它就正常工作了。
<details>
<summary>英文:</summary>
I found the answer by the comment. The params that the constructor takes comes from the instace we create. I had only specified one param in the instance and my contructor took 3 arguments. It worked after i changed the instance.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论