文章目录
1. 类和对象2. Trait3. 模式匹配4. 正则5. 异常处理6. 提取器7. 文件 IO学自 /scala/scala-tutorial.html
1. 类和对象
object myClass {import java.io._class Point(xc : Int, yc : Int){var x : Int = xcvar y : Int = ycdef move(dx:Int, dy:Int): Unit ={x += dxy += dyprintln("x : " + x)println("y : " + y)}}// 继承,只能单继承class Piont3D( val xc : Int, val yc : Int,val zc : Int) extends Point(xc, yc){var z : Int = zcdef move(dx:Int, dy:Int, dz:Int): Unit ={x += dxy += dyz += dzprintln("x : " + x)println("y : " + y)println("z : " + z)}}def main(args: Array[String]) = {val p1 = new Point(10, 20)p1.move(2, 3)// x : 12// y : 23val p2 = new Piont3D(10, 30, 50)p2.move(1,2,3)// x : 11// y : 32// z : 53val fred = new Employeefred.name = "Fred"fred.salary = 50000println(fred) // myClass$Employee[name=Fred][salary=50000.0]}class Person {var name = ""override def toString = getClass.getName + "[name=" + name + "]"}class Employee extends Person {var salary = 0.0override def toString = super.toString + "[salary=" + salary + "]"}}
2. Trait
// Trait 特征, 很像 Java 的抽象类trait Equal {def isEqual(x : Any) : Booleandef isNotEqual(x : Any) : Boolean = !isEqual(x)}class Point2(xc : Int, yc : Int) extends Equal {var x : Int = xcvar y : Int = ycdef isEqual(obj : Any) = {obj.isInstanceOf[Point2] && obj.asInstanceOf[Point2].x == x}}
必须实现 没有实现的isEqual
,或者 声明 Point2 为抽象类abstract class Point2
val p3 = new Point2(2, 3)val p4 = new Point2(2, 4)val p5 = new Point2(3, 3)println(p3.isNotEqual(p4)) // falseprintln(p3.isNotEqual(p5)) // trueprintln(p3.isNotEqual(2)) // true
3. 模式匹配
object myMatch {def main(args: Array[String]) ={println(matchTest(3)) // manyprintln(matchTest(2)) // twoprintln(matchTest(1)) // oneprintln(matchTest1("two")) // 2println(matchTest1("test")) // othersprintln(matchTest1(1)) // oneprintln(matchTest1(6)) // isInt, 顺序遇到符合的就退出,剩余的不匹配val alice = new Person("alice", 18)val bob = new Person("bob", 19)val michael = new Person("michael", 20)for(p <- List(alice, bob, michael)){p match {case Person("alice", 18) => println("hi, alice")case Person("bob", 19) => println("hi, bob")case Person(name, age) => println(name + " " + age)}}// hi, alice// hi, bob// michael 20}def matchTest(x : Int) : String = x match {case 1 => "one"case 2 => "two"case _ => "many" // 类似 default}def matchTest1(x : Any) : Any = x match {case 1 => "one"case "two" => 2case y : Int => "isInt" // 是不是 Int 类型case _ => "others"}// 样例类case class Person(name : String, age : Int)}
4. 正则
// 正则表达式import scala.util.matching.Regexval pat1 = "Scala".rval s = "Scala is scalable and cool"println(pat1 findFirstIn s) // Some(Scala)val pat2 = new Regex("(S|s)cala") // 首字母 S or sprintln((pat2 findAllIn s).mkString(" - ")) //使用分隔符连接所有匹配// Scala - scalaprintln(pat2 replaceFirstIn(s, "Java"))// Java is scalable and coolprintln(pat2 replaceAllIn(s, "Java"))// Java is Javable and cool
5. 异常处理
// 异常处理import java.io.FileReaderimport java.io.FileNotFoundExceptionimport java.io.IOExceptiontry{val f = new FileReader("input.txt")}catch {case e : FileNotFoundException => {println("missing file!")}case e : IOException => {println("IO Exception")} // 一般把具体的异常写在前面,否则捕获了一个普遍的异常,后面的具体异常没有捕获}// missing file!finally {// 都会执行的部分println("finally step")} // finally step
6. 提取器
// 提取器是一个带有unapply方法的对象def apply(user : String, domain : String) = {user + "@" + domain}def unapply(email : String) : Option[(String, String)] = {val parts = email split "@"if(parts.length == 2)Some(parts(0), parts(1))elseNone}println(apply("michael", "")) // michael@println(unapply("michael@")) // Some((michael,))println(unapply("michael csdn")) // None
object myExtractor {//提取器使用模式匹配def main(args : Array[String]) = {val x = myExtractor(5) // 自动调用applyprintln(x) // 10x match{// 在提取器对象中使用 match 语句是,unapply 将自动执行case myExtractor(num) => println(x, num) // 自动调用 unapply (10,5)case _ => println("无法计算")}}def apply(x : Int) = {x*2}def unapply(z : Int) = {if(z%2 == 0)Some(z/2)elseNone}}
7. 文件 IO
object MyIO {import java.io._def main(args: Array[String]): Unit = {// 写入文件val writer = new PrintWriter(new File(("test.txt")))writer.write("scala hah\nhello michael") // 产生文件 test.txt (内容scala hah...)writer.close()// 从屏幕获取输入val input = scala.io.StdIn.readLine()println(input) // 讲输入的内容打印出来// 从文件读取import scala.io.SourceSource.fromFile("test.txt").foreach{print}// scala hah// hello michael}}