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"
*/



No comments:

Post a Comment

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...