我是Kotlin开发的新手。我试图创建一个简单的示例来了解主要构造函数和次要构造函数,因此我引用了以下发布的链接。 但是,尽管我从this link
复制了以下代码,但下面创建的类似乎存在错误请让我知道如何修改以下发布的类,以便我可以运行代码。
MainActivity :
class MainActivity : AppCompatActivity() {
val LOG_TAG : String = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var p1 = CustomPerson("Ar", "Agi", 25632909)
//nonScopingFunc1(p1)
Log.d(LOG_TAG, "p1: " + p1.address)
}
/*private func nonScopingFunc1 (p:CustomPerson) : CustomPerson {
var person : Person = getPersonName(p)
var person : Person = getPersonAddress(p)
var person : Person = getPersonPhone(p)
}*/
}
customClass
class CustomPerson (_name: String, _address: String, _phoneNum: Long) {
var name: String
var address: String
var phoneNum: Long
init {
println("Initialized a new Person object with name = $name , address = $address and phoneNum = $phoneNum")
}
}
答案 0 :(得分:1)
我认为您错过了一些要从链接复制的行:
class Person(_name: String, _age: Int, _salary: Int) {
// Member Variables (Properties) of the class
var name: String
var age: Int
var salary: Int
// Initializer Block
init {
this.name = _name
this.age = _age
this.salary = _salary
println("Initialized a new Person object with Name = $name , age = $age and salary = $salary")
}
}
答案 1 :(得分:0)
不需要阴影变量
class CustomPerson (private val name: String,private val address: String, private val phoneNum: Long) {
init {
println("Initialized a new Person object with name = $name , address =
$address and phoneNum = $phoneNum")
}
}