Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

syntax - Kotlin secondary constructor

How do I declare a secondary constructor in Kotlin?

Is there any documentation about that?

Following does not compile...

class C(a : Int) {
  // Secondary constructor
  this(s : String) : this(s.length) { ... }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update: Since M11 (0.11.*) Kotlin supports secondary constructors.


For now Kotlin supports only primary constructors (secondary constructors may be supported later).

Most use cases for secondary constructors are solved by one of the techniques below:

Technique 1. (solves your case) Define a factory method next to your class

fun C(s: String) = C(s.length)
class C(a: Int) { ... }

usage:

val c1 = C(1) // constructor
val c2 = C("str") // factory method

Technique 2. (may also be useful) Define default values for parameters

class C(name: String? = null) {...}

usage:

val c1 = C("foo") // parameter passed explicitly
val c2 = C() // default value used

Note that default values work for any function, not only for constructors

Technique 3. (when you need encapsulation) Use a factory method defined in a companion object

Sometimes you want your constructor private and only a factory method available to clients. For now this is only possible with a factory method defined in a companion object:

class C private (s: Int) {
    companion object {
        fun new(s: String) = C(s.length)
    }
}

usage:

val c = C.new("foo")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...