存在类型和类型成员的Scala类型推断 [英] Scala type inference for existential types and type members

查看:111
本文介绍了存在类型和类型成员的Scala类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码无法编译:

trait A[F] {
  def find(x: Int): F
  def fill(f: F): Unit
}

object TestA {
  def test[T <: A[F] forSome { type F }](t: T) =
    t.fill(t.find(0))
}

它返回以下编译错误:

test.scala:8: error: type mismatch;
 found   : (some other)F(in type T)
 required: F(in type T)
    t.fill(t.find(0))
                 ^

但是以下代码符合要求:

However the following code complies just fine :

trait B[F] {
  type R = F
  def find(x: Int): R
  def fill(f: R): Unit
}

object TestB {
  def test[T <: B[F] forSome { type F }](t: T) =
    t.fill(t.find(0))
}

我在这里有两个问题:

  1. 我希望第一段代码可以编译.为什么不呢?

  1. I expect the fist piece of code to compile. Why does it not?

如果有充分的理由不能编译第一段代码,出于同样的原因,我希望第二段代码也不会编译.然后如何成功编译?

If there is a good reason why first piece of code does not compile, I would expect the second to not compile either, for the same reason. How then, does it compile successfully?

这些都是错误吗?

推荐答案

我不知道编译器为何区分这两段代码.基本上,代码不会编译,因为find返回的类型和fill期望的类型不必与F相同,至少如果在两个上调用了findfill不同的对象.

I don't know why the compiler differentiates the two pieces of code. Basically, the code doesn't compile because the type returned by find and the type expected by fill don't have to be the same F, at least if find and fill were called on two different objects.

您可以使用以下代码编写第一段代码:

You could make the first piece of code to compile with:

def test[T <: A[F], F](t: T) =
  t.fill(t.find(0))

您可以使第二段代码不与以下代码一起编译:

And you could make the second piece of code not to compile with:

def test[T <: B[F] forSome { type F }](t: T, u: T) =
  t.fill(u.find(0))

这应该是评论而不是答案,但是我还没有50的声誉.

This should be rather a comment than an answer, but I don't have 50 reputation yet.

这篇关于存在类型和类型成员的Scala类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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