https://kotlinlang.org logo
Title
h

Hullaballoonatic

04/17/2019, 8:00 PM
i tend to prefer the following when working with non-traditional class constructors:
data class Foo {
    companion object {
        operator fun invoke(): Foo {
        
        }
    }
}
a

Andrew Gazelka

04/17/2019, 8:07 PM
mmm kinda looks hacky to me
h

Hullaballoonatic

04/17/2019, 8:09 PM
yeah, a large portion of it comes down to how unconventional kotlin's companion objects are
but also, maybe just use type aliases?
b

bdawg.io

04/17/2019, 9:36 PM
I’d probably suggest doing
fun Foo() = Foo(someValue)
instead
g

gildor

04/18/2019, 1:06 AM
For me it looks fine, pretty popular idiom
fun Foo() = Foo(someValue)
is also fine, but it will conflict with class if class has the same signature of constructor, so you cannot have private constructor and builder with some additional logic:
class Foo private constructor(val value: String)

fun Foo(rawWalue: String?) = Foo(requireNotNull(rawWalue))
so invoke operator in companion still pretty useful
b

bdawg.io

04/18/2019, 2:33 AM
Isn't
Foo()
via companion object
invoke()
still just as ambiguous if the class has that same constructor?
g

gildor

04/18/2019, 2:33 AM
No
The same with Foo builder function will not work https://pl.kotl.in/fEWGXae7D
First sample works only with private constructor tho, otherwise it will be ambiguous. But it’s not a problem, because this invoke operator usually used to hide real constructor