使用依赖于路径的类型作为类参数 [英] Use of path-dependent type as a class parameter
本文介绍了使用依赖于路径的类型作为类参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个类,它接受一个具有类相关类型的参数,就像我经常为方法所做的那样.然而,令我惊讶的是,这不起作用:
I want to have a class which takes a parameter with a class-dependent type, as I've often done for methods. However, to my surprise, this didn't 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?
推荐答案
一种看起来可以接受的解决方法(不能在没有额外强制转换的情况下创建无效的 F
):
A workaround which seems acceptable (can't create an invalid F
without 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)
}
这篇关于使用依赖于路径的类型作为类参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文