https://kotlinlang.org logo
#announcements
Title
# announcements
a

Adriano Celentano

11/22/2019, 10:47 AM
As there are so many ressources about domain modeling these days, i had today a use Case where i thought it would make sense. I want to validate a Document and return a type ValidatedDocument Then i want to upload and only accept the type ValidatedDocument for it But my Problem is that ValidatedDocument can not only be created from my validation method but also just by calling the constructor. Is there sth obvious i am missing ?
Copy code
data class Document(val uri: Uri)

data class ValidatedDocument(val uri: Uri)

fun validateDocument(document: Document): ValidatedDocument {
    val valid = true
    if(valid) {
        return ValidatedDocument(documentUpload.uri)
    } else {
        throw IllegalArgumentException("not valid")
    }
}

fun uploadDocument(validatedDocument: ValidatedDocument) {

}

fun main() {
    val doc = Document(uri = Uri.EMPTY)

    val validDoc = validateDocument(doc)

    uploadDocument(validDoc)
}
m

molikuner

11/22/2019, 11:00 AM
Copy code
data class Document(val uri: String)

class ValidatedDocument private constructor(val uri: String) {
    companion object {
        fun create(doc: Document): ValidatedDocument {
            val valid = true;
            return if (valid) {
                ValidatedDocument(doc.uri)
            } else {
                throw IllegalArgumentException("not valid")
            }
        }
    }
}

fun main() {
    val doc = Document(uri = "Uri.EMPTY")
    val validDoc = ValidatedDocument.create(doc)
}
You can mark
ValidatedDocument
as
data class
but then there will be a
.copy
function, which you don’t want, so you probably need to overwrite
equals
,
toString
, etc. yourself.
Or, what I would prefer:
Copy code
data class Document(val uri: String) {
    fun validate(): ValidatedDocument = ValidatedDocument(uri)
}

data class ValidatedDocument(val uri: String) {
    init {
        val valid = true
        require(valid) { "not valid $uri" }
    }
}
a

Adriano Celentano

11/22/2019, 11:37 AM
@molikuner thanks for your ideas, i was thinking in similar ways. Actualy i had the validation originally inside the init block. But i forgot to mention that my validation has dependencies and is a bit more complex. Appearently i will have to use a normal class instead of a data class. Too bad for the boiler plate
u

Ubi

11/22/2019, 12:11 PM
Example_kt.kt
@Adriano Celentano You can use validation rules as parameter function.
2 Views