Calling a secondary constructor from a primary constructor


Hi All,

I’ve two questions:

1 - How to define a secondary constructor in Kotlin ?

2 - Is it possible to call a SECONDARY constructor from a PRIMARY constructor ?


In Kotlin only primery constructor.

But you can do smth like this

class Greeter(val name : String) {
  fun greet() {
  println(“Hello, ${name}”);

fun Greeter(name: Int) = Greeter(name.toString())   

fun main(args : Array<String>) {


Probably there is a good explanation for it, but I don't get the motivation, for having only a single constructor.

In your example, instead of having a public function out of class to initiate it, wouldn’t it be good to have it inside and as a Construtor ?

class Greeter(val name: String) {   fun Greeter(name: Int) {   supert(name.toString)   }   fun greet() {   /// ....   } }


Because if we have default arguments, you can cover most cases in single constructor.

I think other constructors are only sugar. They disappointment me some times. It is better to use factory methods for this purpose.
The advantage of using the ordinary function to emulate constructor is possibility to add it in any library without changing code. I think it is cool.