学自 https://www.runoob.com/scala/scala-tutorial.html
object myClass {
import java.io._
class Point(xc : Int, yc : Int){
var x : Int = xc
var y : Int = yc
def move(dx:Int, dy:Int): Unit ={
x += dx
y += dy
println("x : " + x)
println("y : " + y)
}
}
// 继承,只能单继承
class Piont3D( val xc : Int, val yc : Int,
val zc : Int) extends Point(xc, yc){
var z : Int = zc
def move(dx:Int, dy:Int, dz:Int): Unit ={
x += dx
y += dy
z += dz
println("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 : 23
val p2 = new Piont3D(10, 30, 50)
p2.move(1,2,3)
// x : 11
// y : 32
// z : 53
val fred = new Employee
fred.name = "Fred"
fred.salary = 50000
println(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.0
override def toString = super.toString + "[salary=" + salary + "]"
}
}
// Trait 特征, 很像 Java 的抽象类
trait Equal {
def isEqual(x : Any) : Boolean
def isNotEqual(x : Any) : Boolean = !isEqual(x)
}
class Point2(xc : Int, yc : Int) extends Equal {
var x : Int = xc
var y : Int = yc
def 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)) // false
println(p3.isNotEqual(p5)) // true
println(p3.isNotEqual(2)) // true
object myMatch {
def main(args: Array[String]) ={
println(matchTest(3)) // many
println(matchTest(2)) // two
println(matchTest(1)) // one
println(matchTest1("two")) // 2
println(matchTest1("test")) // others
println(matchTest1(1)) // one
println(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" => 2
case y : Int => "isInt" // 是不是 Int 类型
case _ => "others"
}
// 样例类
case class Person(name : String, age : Int)
}
// 正则表达式
import scala.util.matching.Regex
val pat1 = "Scala".r
val s = "Scala is scalable and cool"
println(pat1 findFirstIn s) // Some(Scala)
val pat2 = new Regex("(S|s)cala") // 首字母 S or s
println((pat2 findAllIn s).mkString(" - ")) //使用分隔符连接所有匹配
// Scala - scala
println(pat2 replaceFirstIn(s, "Java"))
// Java is scalable and cool
println(pat2 replaceAllIn(s, "Java"))
// Java is Javable and cool
// 异常处理
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
try{
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
// 提取器是一个带有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))
else
None
}
println(apply("michael", "csdn.net")) // michael@csdn.net
println(unapply("michael@csdn.net")) // Some((michael,csdn.net))
println(unapply("michael csdn")) // None
object myExtractor {
//提取器使用模式匹配
def main(args : Array[String]) = {
val x = myExtractor(5) // 自动调用apply
println(x) // 10
x 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)
else
None
}
}
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.Source
Source.fromFile("test.txt").foreach{
print
}
// scala hah
// hello michael
}
}