scala模式匹配、类型系统

1.scala模式匹配

  • scala 中没有switch case 用match代替
  • :paste可以在命令还下输入多行,最后编译执行
    def bigData(data:String){
        data match{
            case "spark" =>println("spark")
            case "hadoop"=>println("hadoop")
            case _ =>println("something else")
        }
    }

2.scala集合模式匹配

  • 根据数据的内容进行判断,执行不同的动作
def data(array:Array[String]){
    array match {
    case Array("scala")=> println("scala")
    case Array("spark",_*)=> println ("spark")
    case Array(a,b,c)=> println(a+":"+b+":"+c)
    case _ =>println("else")
    }
}

3.scala样例类模式匹配

  • 相当于java中的bean
class Person
case class Worker(name:String,salary:Double) extends Person
case class Student(name:String,score:Double) extends Person

def sayHi (person:Person){
person match{
case Student (name,score) =>println("i am student "+name +score)
case Worker (name,salary) =>println("i am worker "+name +salary)
case _ => println("unknow")
}}

sayHi(Worker("spark",6.5))
sayHi(Student("spark",6.5))

4.scala类型系统

// 相对于java中的泛型
class Person[T](val content :T){
def getContent(id:T)= id+"---"+content
}
val p = new Person[String]("spark")
p.getContent("scala")

5.scala视图界定

//支持动态类型传入
scala> class Compare [T:Ordering](val n1:T,val n2:T){
     | def bigger(implicit ordered:Ordering[T])=if(ordered.compare(n1,n2)>0) n1
else n2}
defined class Compare

scala> new Compare[Int](8,3).bigger
res10: Int = 8

scala> new Compare[String]("spark","hadoop").bigger
res11: String = spark

6.implicit隐式转换

//访问方法时如果没有该方法,编译器会自动寻找
import scala.io.Source
import java.io.File
class RicherFile(val file:File){
  def read = Source.fromFile(file.getPath()).mkString
}

class File_Implicits(path:String)extends File(path)
object File_Implicits{
  implicit def file2RicherFile(file:File)= new RicherFile(file) //file -> RicherFile
}

object FileImplicit{
  def main(argss :Array[String]){
    println(new File_Implicits("e:\\test.txt").read)
  }
}
展开阅读全文

没有更多推荐了,返回首页