Last active
December 25, 2015 01:59
-
-
Save spoertsch/6899122 to your computer and use it in GitHub Desktop.
IPSWAYS Scala Meetup - OO
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
// object orientation | |
trait Player | |
case class EmptyPlayer() extends Player | |
case class NamedPlayer(name: String) extends Player | |
case class Score(p1: Int, p2: Int) | |
// Vorteil case class: toString, hashcode, copy, == vs. eq | |
val scoreA = Score(1, 2) | |
scoreA.toString() | |
scoreA.hashCode() | |
scoreA.## | |
scoreA.copy() | |
val scoreB = scoreA.copy(p2 = 123) | |
// == Prüft Objekt-Gleichheit | |
scoreB == scoreA | |
scoreA == Score(1, 2) | |
// eq prüft referentielle Gleichheit | |
scoreA eq Score(1, 2) | |
val scoreC = scoreA | |
scoreA == scoreC | |
scoreA eq scoreC | |
// Companion object -> singleton, factory methoden bzw. statische unitilities | |
object MatchHolder { | |
class Match(player1: Player, player2: Player, score: Score) { | |
// Option | |
def getWinner: Option[Player] = { | |
// Pattern Matching | |
score match { | |
case Score(s1, s2) if s1 > s2 => Some(player1) | |
case Score(s1, s2) if s1 < s2 => Some(player2) | |
case _ => None | |
} | |
} | |
override def toString() = s"Match(${player1}, ${player2}, ${score})" | |
} | |
// companion object | |
object Match { | |
def apply(player1: Player, player2: Player, score: Score) = new Match(player1, player2, score) | |
def apply(score: Score) = new Match(EmptyPlayer(), EmptyPlayer(), score) | |
} | |
} | |
import MatchHolder.Match | |
// Neues Match über Konstruktur | |
val match1 = new Match(NamedPlayer("Timo"), NamedPlayer("Jan"), Score(2, 5)) | |
// Neues Match über Factory Methode 1 | |
val match2 = Match(Score(2,3)) | |
// Neues Match über Factory Methode 2 | |
val match3 = Match(NamedPlayer("Timo"), NamedPlayer("Jan"), Score(4, 5)) | |
// get or else default value | |
val winner2 = match3.getWinner.getOrElse(EmptyPlayer()) | |
// Pattern Matching mit Klassen | |
winner2 match { | |
case NamedPlayer(name) => s"And the winner is ${name}" | |
case EmptyPlayer() => "No player won the match." | |
case _ => "Illegal input" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment