Value classes are a special mechanism in Scala that is used to help the compiler to avoid allocating run time objects.
值类是Scala中的一种特殊机制,用于帮助编译器避免分配运行时对象。
This is done by defining a subclass of AnyVal. The only parameter it excepts is the datatype whose value is to be redefined. This is used to redefine all value types except the hashCode and equals.
这是通过定义AnyVal的子类来完成的 。 它唯一的参数是要重新定义其值的数据类型。 这用于重新定义除hashCode和equals之外的所有值类型。
The value types that can be redefined are Char, Int, Float, Double, Long, Short, Byte, Unit, and Boolean.
可以重新定义的值类型为Char , Int , Float , Double , Long , Short , Byte , Unit和Boolean 。
Syntax:
句法:
The syntax for creating a value class in Scala,
在Scala中创建值类的语法,
case class class_name(val val_ name : datatype) extends AnyVal
The value class can have methods that are used to redefine the values or wrap the value used at the time of object creation to a different value.
值类可以具有用于重新定义值或将对象创建时使用的值包装为其他值的方法。
Some points to remember about value class,
关于价值舱,要记住一些要点,
The main purpose of value class is to optimize the program by avoiding run time allocations.
值类的主要目的是通过避免运行时分配来优化程序。
The value class cannot be inherited by other classes.
值类不能被其他类继承。
The value class cannot be nested.
值类不能嵌套。
The value class is used to redefine all value types except the hashCode and equals.
值类用于重新定义除hashCode和equals之外的所有值类型。
It can have only methods (def) as its member i.e. no variable is allowed.
Scala程序了解价值类的概念 (Scala program to understand the concept of value class)
// Program to show the working of
// value class in Scala
class valueClass(val str: String) extends AnyVal {
def doubleprint() = str + str
}
object myObject {
def main(args: Array[String]) {
val obj = new valueClass("Scala ")
println(obj.doubleprint())
}
}
Output:
输出:
Scala Scala
Explanation:
说明:
Here, we have created a value class in Scala named valueClass for string type which has a function named doubleprint that stores the string twice in the object.
在这里,我们在Scala中为字符串类型创建了一个名为valueClass的值类,该值类具有一个名为doubleprint的函数,该函数将字符串在对象中存储两次。
Generally, the value Class is used to store the same data as in the object and it just functions to improve the performance.
通常,值Class用于存储与对象中相同的数据,它仅用于提高性能。
什么是价值类? (What value class does?)
The value class acts as a wrapper class to other types. And the instances of wrapper class are not created at the compile time which improves the performance as less initialization is to be done and compiler time.
值类充当其他类型的包装器类。 而且,包装类的实例不是在编译时创建的,这可以提高性能,因为需要执行的初始化和编译时间更少。