定义一个方法,其返回类型是该方法参数的单例类型 [英] Defining a method whose return type is the singleton type of an argument of that method

查看:20
本文介绍了定义一个方法,其返回类型是该方法参数的单例类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仍在为 this.types(单例类型)苦苦挣扎.假设这个场景:

Still struggling with this.types (singleton 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
}

以下失败:

def test(sys: Sys[Access]): Unit =
  sys.in("v1") { implicit a =>
    val r = Ref.single(44)
    a.set(r)
  }

因为显然 r 的类型是 Ref[Access, Int] 而不是 Ref[a.type, Int].我的猜测是问题是我需要像

because apparently r is of type Ref[Access, Int] and not 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"...

任何想法如何解决这个问题.需求是我没有明确地用类型注释调用.也就是说,出于可理解的原因,我不想Ref.single[a.type, Int](44)(a).

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.

编辑

作为澄清,参考在线程 通过将类型参数与参数的依赖于路径的类型相匹配来约束操作 -- 另外我想要的是创建的可能性对象(Refs)不是通过使用工厂方法 Access 中而是在外部的某个地方(例如使用new 语句).因为系统不能被 Access 的定义所限制,所以我必须能够用更多的对象来扩展它.

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 (e.g. with a new statement). Because the system cannot be limited by the definition of Access, I must be able to extend it with further objects.

推荐答案

您有多种可能性.使用 Scala 2.8/2.8.1,您可以使用私有选项 -Ydependent-method-types,然后使用您的解决方案

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

def single[ A <: Access, V ]( v: V )( implicit a: A ) : Ref[ a.type, V ] = // ...

编译正常.

如果你想避免依赖方法类型,因为它是一个私有选项,你仍然可以通过显式键入对Ref.single的调用来编译你的第一个提案:

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:

  val r = Ref.single[a.type, Int](44)

不过,您需要指定类型,因为永远不会推断出单例类型.您的问题与未推断出单例类型的问题不同,但与之相关:请参阅 如何正确地对这个 HList 进行类型注释?

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?

这篇关于定义一个方法,其返回类型是该方法参数的单例类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆