Skip to content

Instantly share code, notes, and snippets.

View bijancn's full-sized avatar

Bijan Chokoufe Nejad bijancn

View GitHub Profile
val x = "Hello"
val r1 = x + " World"
val r2 = x + " World"
val x = new java.lang.StringBuilder("Hello")
val r1 = x.append(" World").toString
val r2 = x.append(" World").toString
var x = 42
x = x + 1
val x = new java.lang.StringBuilder("Hello")
val r1 = x.append(" World").toString
// 'Hello World'
val r2 = x.append(" World").toString
// 'Hello World World'
val r1 = (new java.lang.StringBuilder("Hello")).append(" World").toString
// 'Hello World'
val r2 = (new java.lang.StringBuilder("Hello")).append(" World").toString
// 'Hello World'
object Cafe {
//@JavaPeople: We don't need semicolons or the return keyword
def buyCoffee(creditCard: CreditCard): Coffee = {
val cup = new Coffee() // new coffee is created
creditCard.charge(cup.price) // side effecting call to outside
cup // cup is returned
}
}
object Cafe {
def buyCoffee(creditCard: CreditCard): (Coffee, Charge) = {
val cup = new Coffee() // new coffee is created
(cup, Charge(creditCart, cup.price)) // cup and charge is returned
}
}
// Can be created without new keyword
case class Charge(creditCard: CreditCard, amount: Double)
Cafe.buyCoffee(creditCard) shouldBe (coffee, charge)
def count(p: A => Boolean): Int
def find(p: A => Boolean): Option[A]
def filter(p: A => Boolean): List[A]
def exists(p: A => Boolean): Boolean
def forall(p: A => Boolean): Boolean
def loadNumberOfItems(url: String): IO[Either[Exception, Int]] = {
val maybeUrl: Option[Url] =
Url(url)
val eitherUrl: Either[Exception, Url] =
maybeUrl.toRight(InvalidUrl)
val eitherJson: Either[Exception, IO[Json]] =
eitherUrl.map(u => request(u))
val eitherResult: Either[Exception, IO[Either[Exception, Int]]] =
eitherJson.map(futureJson =>
futureJson.map(json => json.getFieldOption("number").flatMap(x => x.as[Int]).toRight(InvalidJson)))