Thursday, 16 August 2018

Cake pattern

(don't read this post if you are eating because it might make you throw up)

trait DataReader {
def readName(): String
}
trait DummyDataReader extends DataReader {
def readName(): String = "bEllA"
}
class GreeterService {
self: DataReader =>
def greet(): Unit = {
val formattedName = self.readName().toLowerCase.capitalize
println("Hi there, " + formattedName)
}
}
object Main extends App {
val greeter = new GreeterService() with DummyDataReader
greeter.greet()
// if you want to know why people hate the cake pattern then here is the answer:
greeter.readName()
// wtf?! It exposes all the methods of all the dependencies! Grim
}
view raw Cake.scala hosted with ❤ by GitHub

Wednesday, 15 August 2018

Partial Unification


/*
This doesnt compile because foo is expecting a type
class which takes one type parameter but Function1
takes two
*/
object DoesntCompile {
def foo[F[_], A](fa: F[A]): String = fa.toString
foo { x: Int => x * 2 }
// which is the same as the following
val meow: Function1[Int, Int] = {x: Int => x * 2}
foo(meow)
}
/*
We can make it compile by creating a type alias, Cat,
which fixes the the first type parameter to be Int
*/
object DoesCompile {
def foo[F[_], A](fa: F[A]): String = fa.toString
type Cat[A] = Function1[Int, A]
val meow: Cat[Int] = {x: Int => x * 2}
foo(meow)
}
/*
This is a bit nasty isn't it!
The other way to make it compile, without defining this
special Cat type alias, is to enable Partial Unification
in our build.sbt, which handles it for us.
scalacOptions += "-Ypartial-unification"
*/



Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning...