is it not possible to call a constructor from a co...
# announcements
g
is it not possible to call a constructor from a constructor in kotlin? ex:
Copy code
class A {
    var x: Int = 0
    var y: Int = 0
    constructor(x: Int) {
        this.x = x
    }
    constructor(x: Int, y: Int) {
        this(x + y)
        this.y = y
    }
}
is syntax error in kotlin for whatever reason
a
you were close
Copy code
class A {
    var x: Int = 0
    var y: Int = 0
    constructor(x: Int) {
        this.x = x
    }
    constructor(x: Int, y: Int) : this(x) {
        this.y = y
    }
}
https://kotlinlang.org/docs/reference/classes.html#secondary-constructors
g
@arekolek but that only allows using parameters to literally just pass to the this(x) constructor
image.png
it seems like something like this is impossible in the bounds of kotlin, unless I'm willing to copy/paste and duplicate the whole code from the other constructor
m
you can use
this(x+y)
g
still doesn't seem like I could do
this(if(x > 0) 1 else -1)
. I know this is a peculiar case and doesn't guarantee the original intent was even a good design in the first place, but I'm switching legacy code into kotlin and there are sometimes code like
Copy code
this(param == CodeEnum.FAIL ? "A" : "B");
and I'm wondering if my only options are copy/pasting duplicate code in constructor or changing the design entirely(this whole fiasco is resulting from the
.instanceBy()
static method design that I'm trying to switch into constructors) Seems like kotlin doesn't allow this though
m
this(run{ if (x > 0) 1 else -1})
it is not very elegant but it works
a
Seems like kotlin doesn't allow this though
I think it does 🤔 https://pl.kotl.in/uZ3lt2wqt
g
oof, I guess it does. I think the compile error when I tried might've been from something else. thanks for all the input
d
And for more complex logic you can use a factory function. It can be made to look like a constructor with the following trick: https://pl.kotl.in/UfQ7NwPPu
👍 1