// Java code
public class User {
String name;
public User(String name) {
this.name = name
}
}
class User{
var name = ""
constructor(name: String) {
this.name = name
}
}
Convert to primary constructor
,提示你可以把程式寫成這樣class User(var name: String) {
}
Primary constructor
Primary constructor
就會有 Secondary constructor
–
Primary constructor
顧名思義就是主要的建構子Primary constructor
class User constructor(name: String) {
}
class User public @Inject constructor(name: String) {
}
class User(name: String) {
}
class User(name: String, age: Int = 18) {
}
Primary constructor
無法包含任何程式碼,如果你需要則可寫在 init 區塊內class User(name: String) {
var userName: String
init {
userName = name
// do something
}
}
class User(name: String) {
var userName = name
}
Unresolved reference: name
class User constructor(name: String) {
var userName = name
init {
userName = name //
}
fun doSomething(){
val sonmeName = name // Unresolved reference: name
}
}
// Java code
public class User {
String userName;
public User(String name) {
this.userName = name
}
public void doSomething() {
String sonmeName = name; // Unresolved reference: name
}
}
name 根本不在 doSomething() 的 scope 內
,因此呼叫得到 name 的只有同在建構子內的 init functionval
or var
即可,引數也能加上存取修飾字(Visibility modifiers)class User constructor(private val name: String) {
var userName = name
init {
userName = name
}
fun doSomething(){
val sonmeName = name
}
}
class Singleton private constructor() {
init {
println("Singleton init")
}
companion object {
val instance = Singleton()
}
}
Singleton()
編譯器會報錯 Cannot access '<init>': it is private in 'Singleton'
因此只能使用 Singleton.instance
–
Secondary constructor
語意上說是次要的建構子,可以理解成輔助 Primary constructor
,並且 Secondary constructor
必須委派 Primary constructor
,如果你忘記委派 Primary constructor
編譯時則會出現 Primary constructor call expected
class Priflie(name: String) {}
class User(name: String) {
constructor(profile: Profile) { // Primary constructor call expected
// ...
}
}
class Priflie(name: String) {}
class User(name: String) {
constructor(profile: Profile): this(profile.name) {
// ...
}
}
// Java code
public class User {
public User(String name) {
// ...
}
public User(Proffile profile) {
this(profile.name)
}
}
class Priflie(name: String) {}
class User(name: String){
init {
println("Primary constructor")
}
constructor(profile: Profile): this(profile.name) {
println("Secondary constructor")
}
}
fun main(){
User(Profile("Aki"))
}
Primary constructor
Secondary constructor
class User {
}