简体   繁体   English

Scala:为什么不能从复合类型成员创建匿名类?

[英]Scala: why can't I create anonymous class from compound type member?

trait Trait1
trait Trait2

object O {
  type Type1 = Trait1
  type Type2 = Trait1 with Trait2

  trait TraitMember1 extends Type1
  // this line fails to compile
  trait TraitMember2 extends Type2

  val anon1 = new Trait1 {}
  val anon2 = new Type1 {}

  val anon3 = new Trait1 with Trait2 {}
  // this line fails as well
  val anon4 = new Type2 {}
}

When you try to compile the code above, the commented lines fail with error class type required but Trait1 with Trait2 found . 当您尝试编译上面的代码时,注释行失败,错误class type required but Trait1 with Trait2 found Why is that? 这是为什么? I can manually mixin all traits in the compound member and create an anonymous class just fine. 我可以手动混合该复合成员中的所有特征并创建一个匿名类。

In http://www.scala-lang.org/old/node/6817.html , Martin explained: 马丁在http://www.scala-lang.org/old/node/6817.html中解释:

I agree it might be useful. 我同意这可能会有用。 It's not quite clear what it should mean, though. 不过,目前尚不清楚它的含义。 Expand all aliases, drop parens and then do linearization? 展开所有别名,删除括号,然后进行线性化? Or do the parents affect linearization, and, if, yes, how? 还是父母影响线性化?如果是,如何? we took the easy way out and outlawed these idioms. 我们采取了简便的方法,并禁止了这些习语。

While that sort of complexity could well be sorted out in the spec and the compiler, the end result might lead to suprises when the spec doesn't align with the user's mental model. 尽管可以在规范和编译器中很好地解决这种复杂性,但是当规范与用户的心理模型不符时,最终结果可能会令人惊讶。

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

相关问题 为什么不能在Scala中为匿名函数指定结果类型? - Why can't I specify a result type for an anonymous function in Scala? 为什么在Scala中的匿名函数内不能有for循环? - why can't I have a for loop inside an anonymous function in scala? 在scala中,类成员的参数化返回类型是匿名函数 - In scala, parameterized return type for class member that is an anonymous function 如何在 Scala 中创建只读 class 成员? - How can I create a read-only class member in Scala? Scala匿名类类型不匹配 - Scala anonymous class type mismatch Scala泛型 - 为什么我不能在泛型类中创建参数化对象? - Scala generics - why I can't create parametrised object inside generic class? 为什么我不能在没有丑陋的匿名类的情况下在Scala中实现这个Java接口 - Why can't I implement this Java interface in Scala without ugly anonymous classes 在Scala中,为什么不能在此处显式使用参数类型? - In Scala, why can't I explicitly use a parameter type here? Scala:为什么修复类型成员会创建Java子类? - Scala: Why does fixing a type member create a Java subclass? 为什么我不能从Scala访问实现Java接口的类中声明的变量? - Why can't I access a variable declared in a class, which implements a Java interface, from Scala?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM