简体   繁体   English

类值参数的类型成员类型不匹配

[英]Type mismatch for type members of class value parameter

Why usage of type members bound to class value parameters generates a "type mismatch" error? 为什么使用绑定到类值参数的类型成员会产生“类型不匹配”错误? For example: 例如:

scala> class A { type t }
defined class A

scala> class B(val a: A)
defined class B

scala> val aInt = new A { type t = Int }
aInt: A{type t = Int} = $anon$1@6ccc7368

scala> val b = new B(aInt)
b: B = B@834518

scala> val i: b.a.t = 1
<console>:11: error: type mismatch;
 found   : Int(1)
 required: b.a.t
       val i: b.a.t = 1
                      ^

The strange thing is that when I use a value which is not defined as a class parameter everything works fine: 奇怪的是,当我使用未定义为类参数的值时,一切正常:

scala> abstract class C { val a: A }
defined class C

scala> val c = new C { val a = aInt }
c: C{val a: A{type t = Int}} = $anon$1@1e815aad

scala> val i: c.a.t = 1
i: c.a.t = 1

What is the reason for such behaviour? 这种行为的原因是什么?

Seems like I've understood what's happening. 好像我已经明白发生了什么。 In the example with class B the value a is converted to type A which has no definite value for type t . 在具有类B的示例中,值a被转换为类型A ,其对于类型t没有确定的值。 In the example with abstract class C the instance c overrides the value of a with aInt which has a concrete type for t . 与抽象类的例子C实例c覆盖的值aaInt其具有用于一个具体类型t In other words, c is not an instance of C : it's an instance of its anonymous subclass. 换句话说, c不是C的实例:它是其匿名子类的实例。

If I change the example stating the type of c as C explicitly then I get the same error as in the first case: 如果我更改了将c的类型明确指定为C的示例,那么我会得到与第一种情况相同的错误:

scala> class A { type t }
defined class A

scala> val aInt = new A { type t = Int }
aInt: A{type t = Int} = $anon$1@3b8590c5

scala> abstract class C { val a: A }
defined class C

scala> val c: C = new C { val a = aInt }
c: C = $anon$1@5f14a3c6

scala> val i: c.a.t = 1
<console>:11: error: type mismatch;
 found   : Int(1)
 required: c.a.t
       val i: c.a.t = 1
                      ^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM