Created
November 24, 2019 19:16
-
-
Save marquesds/884c5cd1ca6a38fc1aa6c633f3b63328 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
import scala.concurrent.Future | |
object AdvancedRecap extends App { | |
// partial functions | |
val partialFunction: PartialFunction[Int, Int] = { | |
case 1 => 42 | |
case 2 => 65 | |
case 5 => 999 | |
} | |
val pf = (x: Int) => x match { | |
case 1 => 42 | |
case 2 => 65 | |
case 5 => 999 | |
} | |
val function: (Int => Int) = partialFunction | |
val modifiedList = List(1,2,3,4).map { | |
case 1 => 42 | |
case _ => 0 | |
} // List(42, 0, 0, 0) | |
val lifted = partialFunction.lift // total function Int => Option[Int] | |
lifted(2) // Some(65) | |
lifted(5000) // None | |
// orElse | |
val pfChain = partialFunction.orElse[Int, Int] { | |
case 60 => 9000 | |
} | |
pfChain(5) // 999 | |
pfChain(60) // 9000 | |
// pfChain(457) // throws a MatchError | |
// type aliases | |
type ReceivedFunction = PartialFunction[Any, Unit] // alias to an complex type | |
def received: ReceivedFunction = { | |
case 1 => println("hello") | |
case _ => println("confused") | |
} | |
received(1) // hello | |
// implicits | |
implicit val timeout = 8000 | |
def setTimeout(f: () => Unit)(implicit timeout: Int) = f() | |
setTimeout(() => println("timeout")) // extra parameter omitted | |
// implicit conversions | |
// 1) implicit defs | |
case class Person(name: String) { | |
def greet = s"Hi, my name is $name" | |
} | |
implicit def fromStringToPerson(name: String): Person = Person(name) | |
"Lucas".greet // fromStringToPerson("Lucas").greet - automatically by the compiler | |
// 2) implicits classes | |
implicit class Dog(name: String) { | |
def bark = println("bark!") | |
} | |
"Lassie".bark // new Dog("Lassie").bark - automatically by the compiler | |
// organize - scope order: | |
// local scope | |
implicit val inverseOrdering: Ordering[Int] = Ordering.fromLessThan(_ > _) | |
List(1, 2, 3).sorted // List(3, 2, 1) - see implicit at sorted signature | |
// imported scope | |
import scala.concurrent.ExecutionContext.Implicits.global | |
val future = Future { | |
println("Hello, I'm from future") | |
} | |
// companion objects of the types included in the call | |
object Person { | |
implicit val personOrdering: Ordering[Person] = Ordering.fromLessThan((a, b) => a.name.compareTo(b.name) < 0) | |
} | |
List(Person("Bob"), Person("Alice")).sorted // List(Person(Alice), Person(Bob)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment