But it looks like that is not possible?
# getting-started
k
But it looks like that is not possible?
p
You can declare a global function with the same name as your class, compute parameters there and then create and return instance using primary constructor.
Copy code
class MyClass(size: Int)

fun MyClass(text: String): MyClass {
   val size = text.length
   return MyClass(size)
}
So you will be able to create object with
MyClass(10)
and
MyClass("abc")
.
k
In my case the parameters are objects of the class itself and I need access to the private variables.
I went with making a function in the class' companion object.
👍 1
p
operator fun invoke()
I guess? 🙂
Copy code
class MyClass(size: Int) {
    companion object {
        operator fun invoke(text: String): MyClass {
            val size = text.length
            return MyClass(size)
        }
    }
}
So again you can call just
MyClass("abc")
k
Oh wow that's cool.
Kind of odd that you cannot do this directly with a constructor.
But that's mostly what I want.
👍 1
e
What might be your use-case? You know you can omit primary constructor
k
The primary constructor makes an object from its more primitive parts and the other one makes it from multiple copies of that object itself.