Skip to content

Instantly share code, notes, and snippets.

@j-didi
Last active June 9, 2020 23:10
Show Gist options
  • Save j-didi/f2343ab53c397b400faeaf8d0f13808e to your computer and use it in GitHub Desktop.
Save j-didi/f2343ab53c397b400faeaf8d0f13808e to your computer and use it in GitHub Desktop.
Kotlin ValueObject by delegated properties
import java.security.InvalidParameterException
import java.util.regex.Matcher
import java.util.regex.Pattern
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
//Domain entities with E-mail property
class Client(email: String) {
val email: String by EmailDelegated(email)
}
class User(email: String) {
val email: String by EmailDelegated(email)
}
//E-mail Value Object
class EmailDelegated<T>(private var email: String) : ReadOnlyProperty<T, String> {
init {
validate(email)
}
override fun getValue(thisRef: T, property: KProperty<*>) = email
private fun validate(value: String) {
val pattern = Pattern.compile("^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+")
val matcher: Matcher = pattern.matcher(value)
if(!matcher.matches()) //Change to domain notification =D
throw InvalidParameterException("Invalid e-mail!")
}
}
fun main() {
val client = Client("silva.jd8@gmail.com")
println(client.email)
val user = User("silva.jd8@gmail.") //Throw exception
println(user.email)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment