What's your thoughts in making a constructor priva...
# getting-started
a
What's your thoughts in making a constructor private and declare an
operator fun invoke(...): Either<Exception, Foo>
. Is it an anti-pattern, given that "constructors" , by convention, should always return an instance of the object. Studying DDD and modelling Entities and wondering where/how to have this business rules/validations.
Copy code
data class Note private constructor(val note: String) {
    companion object {
        operator fun invoke(note: String): Either<Exception, Note> {
            if (note.length > 42) {
                return Either.Failure(TooLongException)
            }
            return Note(note)
        }
    }
}
s
I strongly recommend you to read this free article from Effective Kotlin book about constructors, builders, and factory methods. tl;dr:
implementing invoke in a companion object to make a fake constructor is very rarely done. I do not recommend it, primarily because it violates Item 12: Use operator methods according to their names.
y
I think it's a pretty good pattern imo. Maybe try using the Raise type from Arrow instead of Either so that your call prefers the happy path
c
The Arrow team is currently prototyping a way to solve this → https://github.com/arrow-kt/arrow-exact Personally, I really dislike the operator usage in these cases.
w
In Kotlin it's a more common pattern to create a function with the same name as a type as a way of constructing this type. Example from standard library is:
Copy code
public inline fun <T> Sequence(crossinline iterator: () -> Iterator<T>): Sequence<T>
Kotlin's constructor methods have the same semantics as regular functions from the outside, they aren't something special, so I'd say you're free to make it return a sum type. By personal preference I'd even prefer a sum type over an exception
r
seems like unnecessary complexity to me for others to understand how your class works. why not just use an explicit factory function that's easier to understand up front?