映射与路径相关的值类型? [英] Map with path-dependent value type?

查看:93
本文介绍了映射与路径相关的值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Scala具有依赖于路径的类型,例如,如果我在内部类中有一个类,则可以将方法的一个参数约束为另一个参数的内部类的实例:

I know that Scala has path-dependent types, so for example if I have a class within an inner class I can constrain one argument of a method to be an instance of the inner class of the other argument:

class Outer { class Inner( x:Int ) }
val o1 = new Outer
val o2 = new Outer
val i11 = new o1.Inner(11)
val i12 = new o1.Inner(12)
val i21 = new o2.Inner(21)
def f[ A <: Outer ]( a:A )( i:a.Inner ) = (a,i)
f(o1)(i11)  // works
f(o1)(i21)  // type mismatch; i21 is from o2, not o1

我可以使用类型投影创建从外部到内部的地图:

And I can create a Map from an Outer to an Inner using a type projection:

var m = Map[Outer,Outer#Inner]()

但是那会允许像o1 -> i21这样的条目,而我不希望这样.是否有任何类型的魔术要求值必须是其键的内部类的实例?也就是说,我想说类似

But that would allow entries like o1 -> i21, and I don't want that to be allowed. Is there any type magic to require that a value be an instance of its key's inner class? That is, I want to say something like

var m = Map[Outer,$1.Inner]()  // this doesn't work, of course

推荐答案

否.

路径相关类型的范围仅限于对象实例,如您所给出的示例:

Path dependent types are scoped to an object instance, as in the example you gave:

def f[ A <: Outer ]( a:A )( i:a.Inner ) = (a,i)

此处,与路径有关的类型依赖于对象引用"a",该对象引用在第二个参数列表的声明范围内.

Here the path-dependent type relies on the object reference "a", which is in scope for the declaration of the second parameter list.

地图定义看起来有点像:

trait Map[A,+B] {
  def get(key: A): Option[B]
  def + [B1 >: B](kv: (A, B1)): This
}

在定义B时,在范围内没有类型为A的对象供您参考.

There is no object of type A in scope here for you to reference when defining B.

正如其他人所暗示的,您可以定义一个新的类似Map类来满足此要求:

As others have hinted, you could define a new similar Map class which fits this requirement:

trait Map2[A <: Outer] {
  def get(key: A): Option[key.Inner]
  def put(key: A)(value: key.Inner): this.type
}

这篇关于映射与路径相关的值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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