Scala中的值类

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.

可以重新定义的值类型为CharIntFloatDoubleLongShortByteUnitBoolean

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,

关于价值舱,要记住一些要点,

  1. The main purpose of value class is to optimize the program by avoiding run time allocations.

    值类的主要目的是通过避免运行时分配来优化程序。

  2. The value class cannot be inherited by other classes.

    值类不能被其他类继承。

  3. The value class cannot be nested.

    值类不能嵌套。

  4. The value class is used to redefine all value types except the hashCode and equals.

    值类用于重新定义除hashCodeequals之外的所有值类型。

  5. 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值