Skip to content

Instantly share code, notes, and snippets.

@wheaties
Last active August 29, 2015 14:03
Show Gist options
  • Save wheaties/7192b40b76cb99e79127 to your computer and use it in GitHub Desktop.
Save wheaties/7192b40b76cb99e79127 to your computer and use it in GitHub Desktop.
Dependent Type Issue
//Define the traits
trait DepF[A]{
type Out
def apply(x: A): Out
}
trait Super[A]{
def dep: DepF[A]
}
//Define real instances
class ToOption[A] extends DepF[A]{
type Out = Option[A]
def apply(x: A) = Some(x)
}
class WithOpt[A](val dep: ToOption[A]) extends Super[A]
//Define a way to build them using dependent types in implicit scope
trait Build[A]{
type Out <: Super[A]
def apply(): Out
}
object Create{
implicit def b[A] = new Build[A]{
type Out = WithOpt[A]
def apply() = new WithOpt(new ToOption[A])
}
def apply[A](implicit builder: Build[A]) = builder()
}
//Test it out on the repl
scala> import Create._
scala> val created = Create[Int]
created: WithOpt[Int] = WithOpt@a3b7e5c
scala> created dep 1
a.dep.Out = Some(1)
scala> def yo[A](x: Option[A]) = x
yo: [A](x: Option[A])Option[A]
scala> yo(created dep 1) //Hoston, we have a problem!
<console>: 67 error: type mismatch;
found : created.dep.Out
required: Option[?]
//without the implicit dependent type, it works...
scala> val w = ew WithOpt(new ToOption[Int])
w: WithOpt[Int] = WithOpt@4a34e4e2
scala> yo(w dep 1)
res45: Option[Int] = Some(1)
@wheaties
Copy link
Author

This is similar to: https://issues.scala-lang.org/browse/SI-5700 but not the same as the type provided in each case is explicitly given. Hence, there should be no ambiguity and without the Create[Int] step there is none!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment