访问量: 10 次浏览
Value类 是一种新的机制,有助于避免在运行时分配对象。AnyVal 定义了值类。
值类是预定义的,它们与 Java 语言的原始类型相对应。
有9种预定义的值类型。Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean.
equals 或 hashCode 不能由一个值类重定义。值类主要用于优化性能和内存。
让我们通过一些例子来理解值类。
例子 #1:
// Scala program to illustrate value class
// Creating a value class and extend with AnyVal
case class C(val name: String) extends AnyVal
// Creating object
object gfg
{
// Main method
def main (args: Array[String])
{
// Creating the instance of the ValueClass
val c = new C("GeeksForGeeks")
c match
{
// new C instantiated here
case C("GeeksForGeeks") => println("Matched with GeeksForGeeks")
case C(x) => println("Not matched with GeeksForGeeks")
}
}
}
输出
Matched with GeeksForGeeks
在上面的代码中,在case类的帮助下定义了一个价值类,这里AnyVal定义了价值类(C)。
价值类包括一个字符串参数。当我们传递与case语句相同的字符串时,将返回true,否则返回false。
例子 #2:
// Scala program to illustrate value class
// Creating a value class and extend with AnyVal
class Vclass(val a: Int) extends AnyVal
{
// Defining method
def square() = a*a
}
// Creating object
object gfg
{
// Main method
def main (args: Array[String])
{
// creating the instance of the ValueClass
val v = new Vclass(5)
println(v.square())
}
}
输出
25
正如我们所看到的,在上面的例子中,创建了一个值类,并且表示为一个 int 。
上面的代码由值类 Vclass 中的一个 def 组成。这里 Vclass 是一个用户定义的值类,它包裹了 Int 参数并封装了一个平方方法。
为了调用平方方法,创建 Vclass 类的对象,如:val v = new Vclass(5)
equals 或 hashCode 。defs 作为成员。