Skip to content

Instantly share code, notes, and snippets.

View madeleine-chercover-hs's full-sized avatar

madeleine-chercover-hs

View GitHub Profile
def eatVegetable(vegetable: Vegetable): String =
vegetable match {
case ChocolateCake(layers, _) if layers > 3 =>
"Now that's what I call a cake - I mean vegetable."
case _ =>
"No, thank you."
}
def eatVegetable(vegetable: Vegetable): String =
vegetable match {
case Pea(colour, isCooked) =>
s"Oh great, a ${if (isCooked) "uncooked" else "cooked" } $colour pea."
case Eggplant(colour, _) =>
s"No matter how I cook this $colour eggplant, it'll still be the blandest vegetable around."
case ChocolateCake(layers, _) =>
s"Yum, a $layers-layer chocolate cake – the best vegetable of all."
}
sealed abstract class Vegetable
case class Pea(colour: String, isCooked: Boolean) extends Vegetable
case class Eggplant(colour: String, weight: Int) extends Vegetable
case class ChocolateCake(layers: Int, isVegetable: Boolean = true) extends Vegetable
def match(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "whatever"
}
def validateLatLong(latitude: Double, longitude: Double): Option[(Double, Double)] =
if (latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180)
None
else
Some((latitude, longitude))
val foo =
validateLatLong(49, 123) match {
case Some((latitude, longitude)) => /* Proceed with validated data */
case None => /* Handle case where no value is returned */
class InvalidLatLongException(latitude: Double, longitude: Double) extends Exception
def validateLatLong(latitude: Double, longitude: Double): Either[InvalidLatLongException, (Double, Double)] =
if (latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180)
Left(InvalidLatLongException(latitude, longitude))
else
Right((latitude, longitude))
val indexedList: List[(EncryptedMessage, Int)] = encryptedMessages.zipWithIndex
val maybeKeyGroups: Map[Option[Long], List[(EncryptedMessage, Int)]] =
indexedList.groupBy { case (message, _) => message.key }
val keyGroups: Map[Long, List[(EncryptedMessage, Int)]] =
maybeKeyGroups.collect { case (Some(key), messageGroup) => (key, messageGroup) }
val sorted: List[Message] = decryptedIndexedList
.sortBy { case (_, index) => index }
.map { case (message, _) => message }