why secondary constructor needs to point to base c...
# announcements
c
why secondary constructor needs to point to base constructor?
d
You mean primary constructor? In that case the reason is that the primary constructor can declare `val`s, which must be initialized.
Example:
Copy code
class Foo(val x: String) {
    constructor() : super() // x is not initialized!
}
c
for example i have a base constructor which take
String
as parameter and secondary constructor takes type
T
d
Please explain what you mean by "base constructor"
c
base == primary constructor
d
Okay. Did my reasoning above not make sense?
c
not sure.
d
If the secondary constructor wouldn't be forced to delegate to the primary one then any properties declared in the primary constructor would never be initialized, which is not good.
Note that you do not have to have a primary constructor
c
a typical example
Copy code
class Foo(xName:String="") {
    var nick:String = xName
constructor(address:String)`:this()`{
    //TODO()
  }
}
here the primary constructor call is required. Its a bad example though 😐
d
Yes, a primary constructor must always be called.
If you dont want that, dont make a primary constructor.
c
why did kotlin team come up with primary constructor?
m
I think most of what you want can be covered with all other things kotlin provides you. You apparantly have a standard implementation of xName (which is the backing field for
var nick
I presume) If you just write it like this:
Copy code
data class Foo(
    var nick: String = ""
    val address: String
)
you can do what you want with your secondary constructor by just saying:
Copy code
val foo = Foo(address = "my value")
d
Because it is very useful when following the very common pattern of "accept constructor parameter and store it in a field":
class MyClass(val value: String)
2
c
hmmm , not sure.
m
Please elaborate what you aren't sure about
c
got the answer , still not sure why they came up with this sort of language design.
m
You probably come from a Java-like background I presume?
c
yes
thanks , i'm off!
m
consider the following example for a tri-point class:
Copy code
final class TriPoint {
    public final int x;
    public final int y;
    public final int z;

    public TriPoint(int x, int y, int z){
        this.x = x;
        this.y = y;
        this.z = z;
    }
    //equals, hashCode, toString, etc.
}
It's very noticable that x,y,z are the driving variables behind the whole class, whenever you initialize the class, you want to initialize x,y,z. kotlin fixes this by lifting those variables inside what's called a primary constructor:
Copy code
data class TriPoint(
    val x: Int,
    val y: Int,
    val z: Int
)
You have effectively said to the compiler; whatever I'm doing, I need to construct x,y,z at least.
c
i got it.
the above example i gave , was typical example where the soln doesn't holds.