Marko Novakovic
12/22/2021, 3:23 PMcreate()
, method that is explicitly named or use invoke
operator function on a companion object
?Vampire
12/22/2021, 4:32 PMAdam Powell
12/22/2021, 4:40 PMMarko Novakovic
12/22/2021, 5:01 PMdave08
12/26/2021, 1:45 PMdave08
12/26/2021, 1:48 PMAdam Powell
12/26/2021, 3:05 PMAdam Powell
12/26/2021, 3:07 PMdave08
12/26/2021, 3:13 PMbut restricts the implementation to only use the public API of the classFor that, you'd need to put the actual implementation in a different module as
internal
... unfortunately Kotlin doesn't yet have package protected classes... whereas:
data class Foo private constructor(val baz: String) {
companion object { operator fun invoke(...) {... return foo }
}
effectively "hides" the constructor even in the same module... unless I'm missing something?Adam Powell
12/26/2021, 6:11 PMinternal
implied above; the idea is to keep the factory implementation "honest" - public API access only, such that anyone in another module could write it if they were so inclinedAdam Powell
12/26/2021, 6:13 PMTypeName(...)
in terms of usability.Adam Powell
12/26/2021, 6:14 PMAdam Powell
12/26/2021, 6:16 PMdave08
12/27/2021, 11:42 AMIf you need private access then the factory also becomes responsible for creating a valid and internally consistent instance.Ok, that's a great point! I finally understood what you meant there with the extra explanations... The real class's constructor should ensure validity/consistency... the factory methods are only for convenience like for using one type to create another (like translating classes from the data layer to the domain layer?). I guess when it comes to `value class`es though, this gets a bit complex... it's easier now with
init
blocks... but constructors can ONLY have one parameter and MUST be it's internal value... so I guess then, we wouldn't use a separate function, but rather a `companion object`'s invoke
operator and hide the main constructor...