Skip to content

Instantly share code, notes, and snippets.

@vkostyukov
Last active August 29, 2015 14:17
Show Gist options
  • Save vkostyukov/34e204ab2b43824d11d5 to your computer and use it in GitHub Desktop.
Save vkostyukov/34e204ab2b43824d11d5 to your computer and use it in GitHub Desktop.
trait R[+A] { self =>
type In
def apply(in: In): A
def map[B](f: A => B): R[B] = new R[B] {
type In = self.In
def apply(in: In) = f(self(in))
}
def flatMap[B](f: A => R[B] { type In = self.In }): R[B] = new R[B] {
type In = self.In
def apply(in: In): B = f(self(in))(in)
}
}
def foo[I, A](a: A): R[A] = new R[A] {
type In = I
def apply(in: In): A = a
}
//
// compiles
//
val a: R[String] = foo[Int, String]("b").map(_ + "a")
// does not compile
//
// Error:(20, 53) type mismatch;
// found : A$A58.this.AA[String]
// required: A$A58.this.AA[?]{type R = A$A58.this.AA[String]#R}
// foo[Int, String]("a").flatMap(x => foo[Int, String](x));}
//
val b: R[String] = a.flatMap(x => foo[Int, String](x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment