• Scala实践6


     

    1  if表达式

    •      Scala中if...else..表达式是有返回值的,如果if和else返回值类型不一样,则返回Any类型。
    scala> val a3=10
    a3: Int = 10
    
    scala> val a4=
    | if(a3>20){
    | "a3大于a4"
    | }else{
    | "a4大于a3"
    | }
    a4: String = a4大于a3
    
    scala> val a5=
    | if(a3>20)"a3大于20"
    a5: Any = ()
    
    scala> println(a5)
    ()
    

      

    2  while表达式

    • while循环
    scala> def gcdLoop(x:Long,y:Long):Long={
         |  var a=x
         |  var b=y
         |    while(a!=0){
         |    val temp=a
         |    a=b%a
         |    b=temp
         |    }
         |  b
         | }
    gcdLoop: (x: Long, y: Long)Long
    
    scala> gcdLoop(8,9)
    res0: Long = 1
    
    scala> gcdLoop(8,4)
    res1: Long = 4
    
    •   while循环的中断
    import scala.util.control.Breaks
    object whilexample {
        def main(args:Array[String]): Unit ={
          var n=1;
          val loop=new Breaks
          loop.breakable{
               while(n<=20){
                  n+=1;
                   if(n==19){
                      loop.break()
                    }
                }
             }
          println(n)
        }
    }
    

      结果如下:

    3  for表达式

    •  for中to示例:
    scala> for(i <- 1 to 3; j <- 1 to 3){
         |   print(i * j + " ")
         | }
    1 2 3 2 4 6 3 6 9
    
    • for中until示例:
    scala> for(i <- 1 until 3; j <- 1 until 3) {
         |   print(i * j + " ")
         | }
    1 2 2 4
    
    • for中的条件判断示例
    scala> for(i <- 1 to 3 if i != 2) {
         |  print(i+" ")
         | }
    1 3
    scala>
    
    • for中的引入变量
    scala> for(i <- 1 to 3; j = 4 - i) {
         |  print(j+" ")
         | }
    3 2 1
    
    • 使用yield关键字,将遍历过程处理结果返回一个值。
    scala> val for5 = for(i <- 1 to 10) yield i
    for5: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    
    scala> print(for5)
    Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    scala> val for5 = for(i <- 1 to 10)
         | print(for5)
    <console>:13: error: recursive value for5 needs type
           print(for5)
                 ^
    
    •  过滤,通过for中的() 添加过滤器(filter),就是if子句。
    object hello{
     def main(args:Array[String]){ 
      val filesHere=(new java.io.File(".")).listFiles
      for(file<-filesHere if(file.getName.endsWith(".scala")))
      println(file)
      }}
    
    D:>scala hello.scala
    .a.scala
    .h.scala
    .hello.scala
    .s.scala

    4  try表达式

    •  抛出异常
    scala> def ha(n:Int){
         | val half=if(n%2==0) print(n/2)
         | else
         |    throw new RuntimeException("n num be even")
         | }
    ha: (n: Int)Unit
    
    scala> ha(7)
    java.lang.RuntimeException: n num be even
      at .ha(<console>:14)
      ... 28 elided
    
    scala> ha(8)
    4
    

      

    • 捕获异常

    捕获异常的语法选择catch子句的原因是与模式匹配保持一致。

     object ExceptionSyllabus {
            def divider(x: Int, y: Int): Float= {
             if(y == 0) throw new Exception("0作为了除数")
              else x / y
            }
            def main(args: Array[String]): Unit = {
                  try {
                   println(divider(10, 3))
                  } catch {
                    case ex: Exception => println("捕获了异常:" + ex)
                  } finally {}
            }
          }
    
    
    D:>scala ExceptionSyllabus.scala
    3.0
    
    //当数字改为(10,0)后
    D:>scala ExceptionSyllabus.scala
    捕获了异常:java.lang.Exception: 0作为了除数
    

      

    5  匹配表达式

    •  Scala中的match表达式类似于其它语言的switch语句,它可用提供多个备选项做选择。
    object frist{
     def main(args:Array[String]){ 
     val firstArg=if(args.length>0)args(0) else ""
      firstArg match{
      case "salt"=>println("papper")
      case "chips"=>println("salsa")
      case "eggs"=>println("bacon")
      case _=>println("huh?")
         }
    	}
      }
    
    D:>scala frist.scala
    huh?
    
    D:>scala frist.scala salt
    papper
    

      

     6  lazy懒值

    • 当val被声明为lazy时,初始化将被推迟,直到我们首次对此取值,适用于初始化开销较大的场景。 通过lazy关键字的使用与否,来观察执行过程
    object Lazy {
        def init(): String = {
          println("init方法执行")
          "嘿嘿嘿,我来了~"
        }
        def main(args: Array[String]): Unit = {
          lazy val msg = init()
          println("lazy方法没有执行")
          println(msg)
        }
      }
    

      结果:

    object Lazy {
        def init(): String = {
          println("init方法执行")
          "嘿嘿嘿,我来了~"
        }
        def main(args: Array[String]): Unit = {
           val msg = init()
          println("lazy方法没有执行")
          println(msg)
        }
      }
    

     结果: 

    7 柯里化

    在函数编程中,将接受多个参数的函数转化为接受单个参数的函数。这一过程称为柯里化

    scala> def mul(x: Int, y: Int) = x * y
    mul: (x: Int, y: Int)Int
    
    scala> println(mul(10, 10))
    100
    
    scala> def mulCurry(x: Int) = (y: Int) => x * y
    mulCurry: (x: Int)Int => Int
    
    scala> println(mulCurry(10)(9))
    90
    
    scala> def mulCurry2(x: Int)(y:Int) = x * y
    mulCurry2: (x: Int)(y: Int)Int
    
    scala> println(mulCurry2(10)(8))
    80
    

      

    • 柯里化的应用:在忽略大小写的情况下,计较是否相等。
    scala> val a = Array("Hello", "World")
    a: Array[String] = Array(Hello, World)
    
    scala> val b = Array("hello", "world")
    b: Array[String] = Array(hello, world)
    
    scala> println(a.corresponds(b)(_.equalsIgnoreCase(_)))
    true
    

      

  • 相关阅读:
    数据结构化与保存
    使用正则表达式,取得点击次数,函数抽离
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    词频统计
    试题----编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个
    试题---求出现重现次数最多的字母,如有多个重复的则都求出来
    试题----为什么Java的string类要设成immutable(不可变的)
    面试题---题目
    复制文件夹中所有内容到指定位置
  • 原文地址:https://www.cnblogs.com/0205gt/p/10983211.html
Copyright © 2020-2023  润新知