i tend to prefer the following when working with n...
# announcements
h
i tend to prefer the following when working with non-traditional class constructors:
Copy code
data class Foo {
    companion object {
        operator fun invoke(): Foo {
        
        }
    }
}
a
mmm kinda looks hacky to me
h
yeah, a large portion of it comes down to how unconventional kotlin's companion objects are
but also, maybe just use type aliases?
b
I’d probably suggest doing
fun Foo() = Foo(someValue)
instead
g
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:
Copy code
class Foo private constructor(val value: String)

fun Foo(rawWalue: String?) = Foo(requireNotNull(rawWalue))
so invoke operator in companion still pretty useful
b
Isn't
Foo()
via companion object
invoke()
still just as ambiguous if the class has that same constructor?
g
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