Last active
April 16, 2017 09:25
-
-
Save ganeshchand/158746d15adb7c6db48cb1d1ac5316ec to your computer and use it in GitHub Desktop.
This file contains 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
trait User { | |
def name: String | |
} | |
//class FreeUser(name: String, upgradeProbality: Double) extends User | |
//class PremiumUser(name: String, loaltyPoint: Double) extends User | |
//val user1 = new FreeUser("John", 0.75) | |
//println(user1.name) doesn't work | |
class FreeUser(val name: String, val upgradeProbality: Double) extends User | |
class PremiumUser(val name: String, val loaltyPoint: Double) extends User | |
//val user1 = new FreeUser("John", 0.75) | |
//println(s"Hello ${user1.name}") | |
// pattern matching | |
object FreeUser { | |
def unapply(user: FreeUser): Option[(String, Double)] = Some((user.name, user.upgradeProbality)) | |
} | |
object PremiumUser { | |
def unapply(user: PremiumUser): Option[(String, Double)] = | |
Some(user.name, user.loaltyPoint) | |
} | |
val user1: User = new FreeUser("John", 0.75) | |
val user2: User = new PremiumUser("Rebacca", 120) | |
def greetUser(user: User): Unit = user match { | |
case FreeUser(name, _) => println(s"Hello $name") | |
case PremiumUser(name, _) => println(s"Hello $name, what can I do for you?") | |
} | |
greetUser(user1) | |
greetUser(user2) | |
List(user1,user2) foreach greetUser | |
// Boolean extractor | |
def sendUpgradeSpam(user: FreeUser) = { | |
val message = s"Hello ${user.name}, congratulations!! You're eleigible for " + | |
s"our premium services. For more information, pleaes visit our site: http://play/premium" | |
println(message) | |
} | |
def isUpgradeEligible(user: FreeUser): Boolean = { | |
if (user.upgradeProbality > 0.6) true else false | |
} | |
// using a function | |
def spam(user: FreeUser) = { | |
if (isUpgradeEligible(user)) println("Yes, Send him an email") | |
else println("No, Don't spam him") | |
} | |
spam(new FreeUser("Joe", 0.4)) | |
// object and pattern matching | |
object UpgradeEligible { | |
def unapply(user: FreeUser): Boolean = | |
if (user.upgradeProbality > 0.6) true else false | |
} | |
val user3 = new FreeUser("Joe", 0.4) | |
/* | |
user3 match { | |
case UpgradeEligible() => println("Yes, Send him an email") // if true | |
case _ => println("No, Don't spam him") // if false | |
} | |
*/ | |
def spamEligibleUsers(user: User): Unit = user match { | |
case freeUser @ UpgradeEligible() => sendUpgradeSpam(freeUser) | |
case _ => // do nothing | |
} | |
spamEligibleUsers(user1) | |
def makeArray[T: ClassTag](elements: T*) = Array[T](elements: _*) | |
makeArray(1, 2 ,3, 4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment