为什么Scala要求存在类型限制通用范围? [英] Why does scala require existential types to restrict a generic bound?

查看:119
本文介绍了为什么Scala要求存在类型限制通用范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有以下类层次结构:

trait Provider[A] {
  def get(): Seq[A]
}

abstract class ProviderImpl[A] extends Provider[A] {
  final override def get(): Seq[A] = Seq()
}

trait HasX {
  def getX: Int
}

trait RefinedProvider[A <: HasX] extends Provider[A]

class TypedProviderImpl extends ProviderImpl[HasX] with RefinedProvider[HasX]

我希望能够做到这一点:

I want to be able to do this:

val provider: RefinedProvider[_] = new TypedProviderImpl()
provider.get() map (_.getX)

但是它不起作用,因为provider.get()的返回类型是Seq[Any],这对我来说似乎是错误的,因为它是RefinedProvider,所以get()应该返回Seq[_ <: HasX].

But it doesn't work, because the return type of provider.get() is Seq[Any] which seems wrong to me because it's a RefinedProvider, so get() should return a Seq[_ <: HasX].

问题:我可以使用存在性类型解决此问题,但是编译器为什么不能为我强制执行此问题?

Question: I can fix the problem with an existential type, but why can't the compiler enforce this for me?

val provider: RefinedProvider[T] forSome { type T <: HasX } = ...

推荐答案

门票 SI- 2385 建议这只是将A[_]解释为A[T] forSome { type T >: Nothing <: Any }的规范的一部分,并且在可能的情况下不能推断出更严格的界限.有人会怀疑规范是否应该随后进行更新.

Ticket SI-2385 suggests this is simply part of the spec to interpret A[_] as A[T] forSome { type T >: Nothing <: Any } and not infer tighter bounds if possible. One could wonder whether the spec shouldn't be updated then.

机票 SI-6169 似乎暗示某些事情将停止工作如果推断出更严格的界限.我不确定如何以及为什么.

Ticket SI-6169 seems to suggest that some things would stop working if tighter bounds were inferred. I'm not sure how and why though.

一个小妥协是您可以缩短

A small compromise is that you can shorten

val provider: RefinedProvider[T] forSome { type T <: HasX }

val provider: RefinedProvider[_ <: HasX]

这篇关于为什么Scala要求存在类型限制通用范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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