[英]Defining a method whose return type is the singleton type of an argument of that method
Still struggling with this.types (singleton types). 仍在与this.types(单例类型)作斗争。 Assume this scenario:
假设这种情况:
trait Sys[A <: Access] {
def in[T](v: String): AccessPrepare[A]
}
trait AccessPrepare[A <: Access] {
val a: A
def apply[T](fun: a.type => T): T
}
object Ref {
def single[A <: Access, V](v: V)(implicit a: A): Ref[A, V] = ???
}
trait Ref[A, V]
trait Access {
def set(r: Ref[this.type, Int]): Unit
}
The following fails: 以下失败:
def test(sys: Sys[Access]): Unit =
sys.in("v1") { implicit a =>
val r = Ref.single(44)
a.set(r)
}
because apparently r
is of type Ref[Access, Int]
and not Ref[a.type, Int]
. 因为显然
r
是Ref[Access, Int]
类型Ref[Access, Int]
而不是Ref[a.type, Int]
。 My guess is the problem is that I would need a line like 我的猜测是问题是我需要一条线
def single[A <: Access, V](v: V)(implicit a: A): Ref[a.type, V] = ...
which isn't compiling as due to "illegal dependent method type"... 由于“非法的依赖方法类型”而未编译...
Any ideas how I can fix this. 关于如何解决此问题的任何想法。 The demand is that I do not explicitly annotate calls with types.
要求是我不明确地用类型注释调用。 That is, I do not want to write
Ref.single[a.type, Int](44)(a)
for comprehensible reasons. 也就是说,我不想写
Ref.single[a.type, Int](44)(a)
对于理解的原因。
EDIT 编辑
As a clarification, with reference to answer "FYI, and to close the question" in thread Constraining an operation by matching a type parameter to an argument's path-dependent type -- what I would like to have in addition is the possibility to create objects (Refs) not by using a factory method in the Access but somewhere outside (eg with a new
statement). 作为澄清,参考线程中的答案“ FYI,并关闭问题”,方法是通过将类型参数与参数的路径相关类型匹配来约束操作 ,此外,我还想创建对象(引用)不是在 Access中使用工厂方法,而是在外部某个地方(例如,使用
new
语句)。 Because the system cannot be limited by the definition of Access, I must be able to extend it with further objects. 因为系统不受Access定义的限制,所以我必须能够用其他对象扩展它。
You have several possibilities. 您有几种可能性。 With Scala 2.8/2.8.1, you can use the private option
-Ydependent-method-types
and then your solution with 在Scala 2.8 / 2.8.1中,可以使用专用选项
-Ydependent-method-types
,然后使用
def single[ A <: Access, V ]( v: V )( implicit a: A ) : Ref[ a.type, V ] = // ...
compiles fine. 编译良好。
If you want to avoid dependent method types because it's a private option, you can still make your first proposal compile by explicitly typing the call to Ref.single
: 如果您希望避免依赖方法的类型,因为它是一个私有选项,您仍然可以通过显式键入对
Ref.single
的调用来使第一个建议编译:
val r = Ref.single[a.type, Int](44)
You need to specify the type, though, as singleton types are never inferred. 但是,您需要指定类型,因为永远不会推断出单例类型。 You problem is not the same as, but related to, the problem that singleton types are not inferred: see How to correctly type-annotate this HList?
您的问题与未推断出单例类型的问题不相同,但相关:请参见如何正确地对此HList进行类型注释?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.