ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

scala 编程思想 --模式匹配

2021-04-25 22:56:17  阅读:122  来源: 互联网

标签:case Int String scala -- color 模式匹配 println def


计算机编程中很大的一部分工作是在进行比较,并基于是否匹配某项条件执行相应的某项条件来执行相应的条件,任何能够使用这项

区配表达式会将一个值与可能的选项进行匹配,所有匹配都以要纟较的值开头,后面跟着match关键字,左花括号和一组可能匹配

package com.test1

object Scala09_test8{
  def matchColor(color:String):String={
    color match {
      case "red" =>"RED"
      case "blue" =>"BLUE"
      case "green" =>"GREEN"
      case _ =>"UNKown color:"+color
    }
  }

  def main(args: Array[String]): Unit = {
    println(matchColor("red"))
  }
}

名称为color的值后面跟着match关键字,以及在花括号中的一组表达式,它们表示要匹配的项,

—下划线的另一种特殊用法,这里,它是一个通配符,

类参数:

在创建新对象时,一般是通过传递某些信息进行初始化,此时可以使用类参数,类参数列表看起来与方法参数列表一样。

package com.test1

object Scala09_test8{
  def matchColor(color:String):String={
    color match {
      case "red" =>"RED"
      case "blue" =>"BLUE"
      case "green" =>"GREEN"
      case _ =>"UNKown color:"+color
    }
  }


  def checkTruth(exp1:Boolean,exp2:Boolean):String={
    var result=""
    result
  }

  def main(args: Array[String]): Unit = {
    println(matchColor("red"))
    println(checkTruth(true, true))
    println(checkTruth(true, false))
    println(checkTruth(false, true))
    println(checkTruth(false, false))

    class ClassArg(a: Int) {
      println(a)

      def f(): Int = {
        a * 10
      }
    }

    class Sum3(a1: Int, a2: Int, a3: Int) {
      def result(): Int = {
        a1 + a2 + a3
      }
    }

    class Sum(args: Int*) {
      def result(): Int = {
        var total = 0
        for (n <- args) {
          total += n
        }
        total
      }
    }

    val ca = new ClassArg(100)
    println(ca.f())
    println(new Sum(1, 2, 3, 4, 5, 6, 7).result())

    //创建新类Family,它接受一个表示家庭成员姓名的可变元参数列表。编写的代码需要满足下列测试
    class Family(args: String*) {
      def familySize(): Int = {
        args.length
      }
    }

    val family1 = new Family("Mom", "Dad", "Sally", "Dick")
    val family2 = new Family("Mom", "Dad", "Sally")
    println(family1.familySize())
    println(family2.familySize())

    //具名参数和缺省参数
    //在创建具有参数列表的类的实例时,可以指定的参数的名字
    class Color(red:Int,blue:Int,green:Int)
    println(new Color(red=80,blue=9,green=100))
    println(new Color(80,9,green=100))

    class Color2(red:Int=100,blue:Int=100,green:Int=100)
    new Color2(100)
    new Color2(20,17)
    new Color2(100)
    new Color2(red=20,green=42)

    class Overloading1{
      def f():Int = {88}
      def f(n:Int):Int = {n+2}
      //重载与返回值类不一样
      //def f(n:Int):Double = {n*2.9}
    }
    
    //构造器
    //初始化是相当容易出错的块,你的代码可能各方面都是对的,但是如果没有正确设置初始条件
    class Coffee(val shots:Int=2,val decaf:Boolean=false,val milk:Boolean=false,val toGo:Boolean =false,val syrup:String=""){
      var result = ""
      println(shots,decaf,milk,toGo,syrup)
      def getCup():Unit={
        if(toGo)
          result+="togcpu"
        else
          result+="HereCup"
      }
    }

  }
}

重载

辅助构造器

类参数列表中的具名参数和缺省参数

package com.test1

class GardenGnome(val height:Double,
                  val weight:Double,
                  val happy:Boolean) {
  println("Inside primary constructor")
  var painted = true
  def magic(level:Int):String={
    "Poof!"+level
  }

  def this(height:Double){
    this(height,100.0,true)
  }

  def this(name:String){
    this(15.0)
    "Paited is true"
  }

}

  • case 类:

类这种机制已经替你完成大量的工作,但是在创建主要用于保存数据的类时,依然有大量的重复代码,但是在创建主要数据的类时,依然有大量的重复氏码,scala会尽可能地消除这种重复性,这正是case类所做的事情,

case class TypeName(args1:Type,args2:Type,……)

package com.test1

object Scala09_test9 {
  def main(args: Array[String]): Unit = {
    case class Dog(name:String)
    val dog1=new Dog("Henry")
    val dog2=new Dog("CLeo")
    val dogs = Vector(dog1,dog2)
    for(item<-dogs){
      println(item.name)
    }
    //与常规类不同,有了case类,我们在创建对象时就不必再使用new 关锓了,在创建Dog和cat对象时可以看到这种变化
    case class Cat(name:String,age:Int)
    val cats=Vector(Cat("miffy",3),Cat("Rags",2))

    //创建case类来表示地址簿中的perion,用三个String分别表示姓 、名和联系信息
    case class Person(xing:String,name:String,address:String)
    val peoples = Vector(Person("Jane","Smile","jane@smile.com"),
      Person("Ron","House","ron@house.com"),
      Person("Sally","Dove","sally@dove.com"))
    println(peoples(0))

    //字符串插值
    //利用字符串插值,你创建的字符串就可惟包含格式化的值,在辽串前面放置s,在你想让scala插值韩国人标识符之前放置一个$
    def fun(s:String,n:Int,d:Double):String={
      s"first:$s,second:$n,third:$d"
    }

    println(fun("hello world",11,3.14))
    //注意,任何以$

    def fun1(n:Int):Int={n*11}
    println(s"fun1(11) is ${fun1(11)}" )

    case class Sky(color:String)
    //在第6行在字符串周围使用三重引号,使得我们可以将sky构造器中的参数用引号引起来的
    println(s"""${new Sky("Blue")}""")
    
    

  }
}

参数化类型

如定 val stringVactor:Vactor[String]=Vactor("Hello","world")

标签:case,Int,String,scala,--,color,模式匹配,println,def
来源: https://blog.51cto.com/u_13887992/2733342

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有