Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Let's check implicit composition in Scala, e.g.:
- new BaseEmailChecker().withLengthMoreThan(10).withDomainCheck("gmail").withEnding(".com")
- // Question: how many times the base function will be executed?
- trait Checker {
- def execute(s: String): Boolean
- }
- class BaseEmailChecker extends Checker {
- override def execute(s: String): Boolean = {
- println("CHECKING THE BASE FUNCTION!")
- s.contains("@") && s.contains(".")
- }
- }
- object CheckerBuilder {
- implicit class RichChecker(base: Checker) {
- def withLengthMoreThan(n: Int) = new Checker {
- override def execute(s: String): Boolean = {
- println("CHECKING LENGTH!")
- base.execute(s) && s.length > n
- }
- }
- def withDomainCheck(domain: String) = new Checker {
- override def execute(s: String): Boolean = {
- println("CHECKING DOMAIN!")
- base.execute(s) && s.contains(domain) // regex would be better than just 'contains'
- }
- }
- def withEnding(ending: String) = new Checker {
- override def execute(s: String): Boolean = {
- println("CHECKING ENDING!")
- base.execute(s) && s.endsWith(ending)
- }
- }
- }
- }
- import CheckerBuilder._
- val checker1 = new BaseEmailChecker()
- val checker2 = new BaseEmailChecker().withLengthMoreThan(10).withDomainCheck("gmail").withEnding(".com")
- // Come on!
- scala> checker1.execute("amitrakov@tala.co")
- CHECKING THE BASE FUNCTION!
- res0: Boolean = true
- scala> checker2.execute("amitrakov@tala.co")
- CHECKING ENDING!
- CHECKING DOMAIN!
- CHECKING LENGTH!
- CHECKING THE BASE FUNCTION!
- res1: Boolean = false
- scala> checker2.execute("amitrakov@gmail.com")
- CHECKING ENDING!
- CHECKING DOMAIN!
- CHECKING LENGTH!
- CHECKING THE BASE FUNCTION!
- res2: Boolean = true
- // summary: the base function is executed only once!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement