scala中类如何定义
在Scala中,可以使用关键字class来定义类,类的基本语法如下:
class 类名 {
// 类的成员变量
var 变量名: 类型 = 初始值
// 类的成员方法
def 方法名(参数列表): 返回类型 = {
// 方法体
}
// 类的辅助构造器
def this(参数列表) {
// 构造器的代码
}
}
其中,类名是类的标识符,变量名是类的成员变量的名称,类型是变量的数据类型,初始值是变量的初始值。方法名是类的成员方法的名称,参数列表是方法的参数列表,返回类型是方法的返回值类型。辅助构造器是用于创建类的对象的辅助方法。
例如,下面是一个简单的Scala类的定义示例:
class Person {
var name: String = ""
var age: Int = 0
def sayHello(): Unit = {
println("Hello, I'm " + name + ".")
}
def setAge(newAge: Int): Unit = {
age = newAge
}
def this(name: String, age: Int) {
this()
this.name = name
this.age = age
}
}
可以通过以下方式创建该类的对象:
val person = new Person()
person.name = "Alice"
person.age = 25
person.sayHello()
person.setAge(30)
person.sayHello()
val person2 = new Person("Bob", 35)
person2.sayHello()
以上代码中,首先创建了一个Person类的对象person,然后设置了其name和age属性,并调用了sayHello方法。接着调用了setAge方法修改了person对象的age属性,并再次调用了sayHello方法。最后通过辅助构造器创建了另一个Person类的对象person2,并调用了sayHello方法
原文地址: http://www.cveoy.top/t/topic/h1Ah 著作权归作者所有。请勿转载和采集!