https://kotlinlang.org logo
Title
a

Ayfri

03/16/2022, 5:59 PM
Hi, is it possible to add an external secondary constructor for a class ? I have a
typealias AABB = Rectangle
with an external "constructor"
fun Rectangle(x: Int = 0, y: Int = 0, width: Int = 0, height = 0) = ...
but it's not present on the type AABB, I also tested with
fun Rectangle.invoke(x: Int ...
but it still doesn't work, is it possible ?
c

Casey Brooks

03/16/2022, 6:01 PM
If the class has a companion object, then you can make an extension on the companion which looks like a constructor:
fun Rectangle.Companion.invoke(...): Rectangle
r

Ruckus

03/16/2022, 6:03 PM
You can just make a to level
fun Rectangle(...)
(or
fun AABB(...)
)
💯 2
a

Ayfri

03/16/2022, 6:04 PM
Oh yes the
invoke
has to be on the Companion object, it kinda works, as I can't directly do
val a = AABB()
but
val a = AABB.invoke()
I just forgot
operator
, it works thanks x)
t

turansky

03/30/2022, 10:13 PM
fun
with similar name, suggested by @Ruckus is more flexible solution in this case