Apache Spark 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

对象定义

Scala支持面向对象编程,使用class定义一个类,在类定义中使用val定义成员变量,用def定义成员方法:

scala> class Calculator {
    val brand: String = "HP"
    def add(m: Int, n: Int): Int = m + n
}
defined class Calculator

使用new 关键字创建一个对象,使用.调用对象的属性和方法:

scala> val calc = new Calculator
calc: Calculator = Calculator@e75a11

scala> calc.add(1, 2)
res1: Int = 3

scala> calc.brand
res2: String = "HP"

OO,呃,可以把代码组织的更漂亮。

请定义类 Person ,有两个属性 name 和age , 分别为String类型和Int类型;一个方法grow,当 grow被调用时,将age加1。