scala讲解---模式匹配,apply()

来源:互联网 发布:大纲软件 编辑:程序博客网 时间:2024/06/06 03:15
第一份代码
abstract class person3{  def speak  def speak1{      }  val name1 : String  var age : Int}trait logger{  def test(pr : String){    print(pr)  }}class logger1 extends logger{  def test1{    test("woshi");  }}class student2 extends person3{      //第一次继承特质要用extends而不是with  def speak =           //重写抽象类可以不谢override关键字    println("nihao")    val name1 = "sdj"  var age = 1 }object person3{  def main(args : Array[String]){//    val a = new student2//    a.speak    val b = new logger1    b.test1  }}
第二份代码
class applytest {  def apply() = "nihao1"  def test{    println("nihao")  }}object applytest{                  //在里面定义的相当于静态方法  var incr = 0  def inc {    incr = incr + 1  }    def apply() = new applytest}object test extends App{  val a = applytest()         //类名后加括号就代表了调用object apply方法,对象后加括号代表调用class的apply方法  println(a())  for(i <- 1 to 10){    applytest.inc  }  println(applytest.incr)}<pre name="code" class="plain">import scala.reflect.ClassTagclass matchcase {  }object matchcase extends App{ /* val value =2  val a = value match {       //模式匹配是有返回值的    case 1 => "one"    case 2 => "two"    case 3 => "three"    case _ => "can't find"  }  val b = value match{            //case 和 if一起使用    case i if i == 1 => "one"    case i if i == 2 => "two"    case _ => "can't find"  }*/  def t[T:ClassTag](obj : T) : String =  obj match {    case i : Int => "int"    case s : String => "String"    case m : matchcase => "matchcase"    case _ => "unknow"  }  println(t(new matchcase))}



0 0