在了解了scala的的基本语法和集合后,本节将阐述scala当中的类、对象与函数。
1 系统、软件以及前提约束
- win10 64位
- 已在idea中学习scala的基本语法
https://www.jianshu.com/p/9bab3c302256 - 已了解了scala当中的数组、集合与迭代
https://www.jianshu.com/p/e419626a266e
2 操作
- 1 object
在idea中创建一个Test.scala,这个就是所谓的静态类,加入以下内容:
//静态类
object Test {
//静态入口方法
def main(array:Array[String]): Unit ={
//调用test无参方法
test();
//调用test无参方法
test;
//调用test有参方法
test("ali")
//调用test1无参方法
test1;
}
//声明test无参方法,调用的时候有两种方式:test , test()
def test(): Unit ={
println("test()")
}
//声明test有参方法,调用的时候有一种方式: test("ali")
def test(name:String): Unit ={
println(name)
}
//申明test1无参方法,可以省略小括号,调用的时候只有一种方式 test1
def test1={
println("test1")
}
}
``
* 2 class
在idea中加入Student.scala,这是一个普通类,修改内容如下:
class Student {
val age = 9;
val name:String = "zhangli";
def test1(): Unit ={
println(age);
}
def test2(): Unit ={
println(name);
}
}
在idea中再次加入Object TestStudent.scala,修改内容如下:
object TestStudent {
def main(array:Array[String]): Unit ={
val student = new Student();
student.test1();
student.test2();
val student1 = new Student;
student1.test1;
student1.test2;
}
}
* 3 构造器
任何一个类都是有默认构造方法的,此方法与类名同名,可以不用显式的申明。无参的构造方法在调用的时候可以不用加小括号。在scala中构造函数分为主构造函数和辅助构造函数。
//定义一个类,默认包含主构造函数
class Time {
private var hr = 0
private var min = 0
//辅助构造函数,包含一个参数
def this (hr : Int) {
this () //调用主构造函数,必须调用
this.hr = hr
}
//辅助构造函数,包含两个参数
def this (hr : Int, min : Int) {
this (hr) //调用辅助构造函数,必须调用
this.min = min
}
}
* 4 apply
在scala命令行中执行以下语句:
class TestApply {
def apply(name:String): Unit ={
println("apply test : "+name)
}
}
//因为默认构造方法没有参数,所以可以不必加括号
val testApply = new TestApply
testApply.apply("ali")
//下面的语句与上面的语句等价,下面语句的写法就是隐式调用apply方法
testApply("ali")
* 5 update
在scala命令行中执行以下语句:
import scala.collection.mutable.Map
val user = Map("ali"->17,"xiaoli"->28)
user.update("ali",20)
//下面的语句等价于上面的语句,隐式调用update方法
user("ali")=6
* 6 value和value_
value以及value_类似于get以及set方法,如此调用更为简便。在scala命令行中执行以下语句:
//定义一个Student
class Student {
var age:Int = 9;
def value = age
def value_(newAge : Int){
age = newAge
}
}
//测试
object TestStudent1 {
def main(array:Array[String]){
val student = new Student1;
student.value_(18);
println(student.value)
}
}
以上就是在idea中创建scala类和使用类的过程。