Using a path dependent type as a class parameter

I want to have a class that accepts a parameter with a class-dependent type, as it often did for methods. However, to my surprise, this did not work:

scala> trait Compiler { trait Config }
defined trait Compiler

// works fine, as expected
scala> def f(c: Compiler)(conf: c.Config) = {}
f: (c: Compiler)(conf: c.Config)Unit

scala> class F(val c: Compiler)(val conf: c.Config)
<console>:8: error: not found: value c
       class F(val c: Compiler)(val conf: c.Config)
                                          ^

Why? And are there any workarounds?

+4
source share
2 answers

A workaround that seems acceptable (cannot create invalid Fwithout additional casts):

class F private (val c: Compiler)(_conf: Compiler#Config) {
  def conf = _conf.asInstanceOf[c.Config]
}

object F {
  def apply(c: Compiler)(conf: c.Config) = new F(c)(conf)
}
+4
source

Regarding why type-dependent types do not work in the base class constructor, the answer is given in section 5.3 of the Scala language specification:

the formal value parameter cannot be part of the types of any of the parent classes or members of the class template

( , " " , ).

, , :

class F private (val conf: Compiler#Config, val c: Compiler) {
    def this(c: Compiler)(conf: c.Config) = this(conf, c)
}
+2

Source: https://habr.com/ru/post/1608823/


All Articles