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

第一份代码

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.ClassTag


class 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值