Last active
June 9, 2020 23:10
-
-
Save j-didi/f2343ab53c397b400faeaf8d0f13808e to your computer and use it in GitHub Desktop.
Kotlin ValueObject by delegated properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("[email protected]") | |
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