简体   繁体   English

用构造函数和伴随对象扩展类

[英]Extends class with constructor and companion object

I would like extend the following class and companion 我想扩展以下课程和同伴

object MyData { // code inside }
class MyData(val data: Struct) extends AnyVal { // code inside }

but get Illegal inheritance from value error when doing try to do this 但是尝试执行此操作时会Illegal inheritance from value错误获取Illegal inheritance from value

class MyDataExtended(override val data: Struct) extends MyData(data)

Taken From: http://docs.scala-lang.org/overviews/core/value-classes.html 摘自: http : //docs.scala-lang.org/overviews/core/value-classes.html

Prior to Scala 2.10, AnyVal was a sealed trait. 在Scala 2.10之前, AnyVal是密封特性。 Beginning with Scala 2.10, however, it is possible to define a subclass of AnyVal called a ''user-defined value class'' which is treated specially by the compiler. 但是,从Scala 2.10开始,可以定义AnyVal的子类,称为“用户定义的值类”,该类由编译器专门处理。 Properly-defined user value classes provide a way to improve performance on user-defined types by avoiding object allocation at runtime, and by replacing virtual method invocations with static method invocations. 正确定义的用户值类提供了一种方法,可通过避免在运行时分配对象以及将虚拟方法调用替换为静态方法调用来提高用户定义类型的性能。

Limitations 限制

Value classes currently have several limitations, in part because the JVM does not natively support the concept of value classes. 值类当前有一些限制,部分原因是JVM本身不支持值类的概念。 Full details on the implementation of value classes and their limitations may be found in SIP-15. 有关值类的实现及其限制的完整详细信息,请参见SIP-15。

Summary of Limitations 限制摘要

  1. must have only a primary constructor with exactly one public, val parameter whose type is not a value class. 必须仅具有一个主构造函数,该主构造函数仅具有一个公共val参数,其类型不是值类。 (From Scala 2.11.0, the parameter may be non-public.) (从Scala 2.11.0开始,该参数可能是非公开的。)

  2. may not have specialized type parameters. 可能没有专门的类型参数。

  3. may not have nested or local classes, traits, or objects 可能没有嵌套或局部的类,特征或对象

  4. may not define a equals or hashCode method. 可能未定义equals或hashCode方法。

  5. must be a top-level class or a member of a statically accessible object. 必须是顶级类或静态可访问对象的成员。

  6. can only have defs as members. 只能将defs作为成员。 In particular, it cannot have lazy vals, vars, or vals as members. 特别是,它不能具有惰性val,var或val作为成员。

  7. cannot be extended by another class. 不能被另一个类扩展。

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

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