``` class Person private constructor(val name: Str...
# announcements
a
Copy code
class Person private constructor(val name: String, val age: Int) : Individual { 
    //stuff 
}

fun Person(name: String, age: Int): Person {
    require(age >= 18)

    return Person(name, age)
}
h
but what if, for example, you want to make an Email class that requires the address provided in the constructor always be valid otherwise it's null?
a
the address is null if its invalid or the Email?
h
is that essentially impossible, and this use a factory method to return the class instance or null based on the field's validity, and then just encourage the class never be otherwise instantiated?
e.g.
val email: Email? = Email(submittedEmailAddress)
a
yeah, you could do that with a factory method. note that in my example the constructor is private, so the only way to create an Instance of
Person
is via the factory method beneath it
h
oh yeah, duh! private constructor. i'm so dumb
i can even use the
invoke
operator function for the factory method
a
but lets look at this exact problem more closely. why are there
EmailAddress
instances that contain faulty addresses? You could check the provided "ab@xy.net" when creating an instance of
EmailAddress
yes,
invoke()
inside the
companion object
works too
h
well, i know it breaks MVC format a bit, but i like when entities can validate themselves
a
there is one downside to this, you must not use
Person.copy()
or directly set
person.age = 14
, because that bypasses the factory method and its checks
h
I'm writing database entities, for context
a
I haven't worked with exposed yet, but you might ask in #C0CG7E0A1, if its possible to use factory methods or if you have to resort to
init { }
hack
h
I ended up going down this massive rabbit hole, because 😳 i wanted my table operator contains methods to differentiate between username, email, and password fields
and the only way i could think to do that was to give them all different classes than just strings
a
if only
inline classes
would be available already 😅
😴 1
h
the embarrassment because i literally want to just write
Copy code
username in table -> existsException
email in table -> exists Exception
instead of
Copy code
table.usernameExists(username) -> existsException
table.emailExists(email) -> existsException
like.... i know that this all just seems silly for just a tiny syntax improvement, but i write in kotlin instead of java so i can eliminate exactly that kind of unnecessary verbosity that plagues java
are inline classes confirmed as a future feature? i know jetbrains asked the community if they wanted them
a
yes, its included in 1.3-RC
😍 1
h
it'll be so nice for working with scientific units