https://kotlinlang.org logo
#getting-started
Title
# getting-started
v

Victor Cardona

12/23/2020, 3:14 PM
I’m having a small issue that is confounding me. I’m trying to gather my validation messages inside a class’ companion object like so:
Copy code
internal companion object {
        internal val validation = object {
            val name_blank: String = "Presenter must have a name"
        }
    }
The problem I’m having is that the name_blank property is not visible anywhere.
Presenter.validation.name_blank // Error, name_blank not resolved
m

Milan Hruban

12/23/2020, 8:32 PM
Hi, if you expose anonymous object (as a return type or public property), it get's exposed as it's supertype (in this case it's
Any
, because you haven't declared any supertype). So the properties are not visible outside of the file. https://kotlinlang.org/docs/object-declarations.html#object-declarations
v

Victor Cardona

12/23/2020, 11:01 PM
Thank you! I had noticed that it was exposed as Any, but that didn’t register with me for some reason. After rethinking my approach here is what I ended up with. This works and allows for additional validations in the future.
Copy code
internal object Validator {
    const val NAME_BLANK: String = "Presenter must have a name"

    internal fun validateName(name: String): String {
        notBlank(name, NAME_BLANK)
        return name;
    }
}
👍 1