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.
它只能有方法( def )作為其成員,即不允許任何變量 。
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.
值類充當其他類型的包裝器類。 而且,包裝類的實例不是在編譯時創建的,這可以提高性能,因為需要執行的初始化和編譯時間更少。
翻譯自: https://www.includehelp.com/scala/value-class.aspx