zoukankan      html  css  js  c++  java
  • Scala 流程空间,函数,异常处理

    • 1,)首先留意一下下边的代码块,他是怎么运行的,貌似在c#中他是出错的,不应该出现这样的写法的,但在scala中侧不然:
     1 package com.dt.study
     2 
     3 /**
     4  * The package path is com.dt.study.
     5  * Created by tommy duan on 2015/11/16.
     6  */
     7 object HelloScala {
     8   var line = ""
     9   do {
    10     line = readLine()
    11     if (!line.isEmpty) println("Read line is:"+line)
    12   } while (line != "")
    13 
    14   def main(args: Array[String]): Unit = {
    15     println("Hello Scala!!!")
    16   }
    17 }

    运行起来后,会等待输入文字,知道输入空位置,直接走入main函数。

    • 2,)object 在scala中是一个对象,对象声明同类一样,是不需要public修饰的,默认就是public
    • 3,)scala object对象内部的函数都是静态的:访问方式为 HelloScala.

    HelloScalaClass

     1 package com.dt.study
     2 
     3 /**
     4  * The package path is com.dt.study.
     5  * Created by tommy duan on 2015/11/16.
     6  */
     7 class HelloScalaClass {
     8   def sayHello(line:String)={
     9     println(line)
    10   }
    11 }
    View Code

    HelloScalaObject

     1 package com.dt.study
     2 
     3 /**
     4  * The package path is com.dt.study.
     5  * Created by tommy duan on 2015/11/16.
     6  */
     7 object HelloScalaObject {
     8   var line=""
     9   def sayHello(line:String):Unit={
    10     println(line)
    11   }
    12 }
    View Code

    class 与 object调用

     1 package com.dt.study
     2 
     3 /**
     4  * The package path is com.dt.study.
     5  * Created by tommy duan on 2015/11/16.
     6  */
     7 object HelloScala {
     8   def main(args: Array[String]): Unit = {
     9     println("Hello Scala!!!")
    10     
    11     HelloScalaObject.sayHello("Hello scala object")
    12     var scalaCls=new HelloScalaClass();
    13     scalaCls.sayHello("Hello scala class") 
    14   }
    15 }

    同样object对象内部的属性对象也是静态的,且内部字段默认scala会给其实现get.set函数(但不考虑var类型,private类型)

    • 4,)val 与var类型
     1 package com.dt.study
     2 
     3 /**
     4  * The package path is com.dt.study.
     5  * Created by tommy duan on 2015/11/16.
     6  */
     7 object HelloScala {
     8   def main(args: Array[String]): Unit = {
     9     println("Hello Scala!!!")
    10 
    11     var line=""
    12     line="hello"
    13     println(line)
    14 
    15     val lineVal="hello"
    16     println(lineVal)
    17     lineVal="test"
    18   }
    19 }

    在idea编译器中17 lineVal="test" 会报错误,编译不通过。

    原因,val是不可以变类型,一旦设置了值后,就不可以更改变量值;而var是可变变量,可以改变值。val像是java中被final修改的变量。

    • scala类和对象中字段的隐藏get set函数实现
     1 package com.dt.study
     2 
     3 /**
     4  * The package path is com.dt.study.
     5  * Created by tommy duan on 2015/11/16.
     6  */
     7 object HelloScala {
     8   def main(args: Array[String]): Unit = {
     9     println("Hello Scala!!!")
    10     
    11     println(HelloScalaObject.line)    
    12     HelloScalaObject.line="sss"
    13     
    14   }
    15 }

    请留意:

    11     println(HelloScalaObject.line)    
    12     HelloScalaObject.line="sss"

    这两行代码,第11行代码隐含了几层含义:

    1,)line是一个public变量;

    2,)调用了HelloScalaObject对象的隐藏line var的get函数;

    第12行除了上边1,)外还有一层含义:调用了HelloScalaObject对象的隐藏line var的set函数;

    函数返回值问题

     1 package com.dtgroup.study
     2 
     3 object HelloStduy {
     4   def main(args: Array[String]): Unit = {
     5     println("Hello Scala")
     6 
     7     var files = (new java.io.File(".")).listFiles()
     8     for (file <- files) println(file)
     9 
    10     val filePath = "spark.txt"
    11     try {
    12       if (!filePath.isEmpty())
    13         throw new RuntimeException("An error thrown.")
    14     } catch {
    15       case e: Exception => println(e.getMessage())
    16     } finally {
    17 
    18     }
    19     
    20     println(returnWithSomething)
    21   }
    22   
    23   def returnWithSomething():String={
    24     var result=""
    25     var items=new Array[String](10)
    26     
    27     for(i<- 0 to 9) items(i)=i.toString    
    28     
    29     result=items.mkString(",")
    30     result
    31   }
    32 }

    输出内容:

    Hello Scala
    ..cache-main
    ..classpath
    ..project
    ..settings
    .in
    .src
    An error thrown.
    0,1,2,3,4,5,6,7,8,9

    我们先不看上边的结果为什么,单想象returnWithSomeThing这是个什么?

    1,)它在scala中是一个函数,函数一般都是使用def来声明;

    2,)在这里它是一个静态函数;

    3,)它的返回值类型为String;

    4,)该函数的最后一行默认就是返回值,这是规定,也是规范;

    5,)def main(args: Array[String]): Unit ,它的返回值类型为Unit,在scala中Unit为空,表示不返回任何类型,同时这里的main函数也是可以不写返回Unit的,格式为:

    def main(args: Array[String])={
       println("hello main")
    }

    6,)函数的调用,如果不需要参数可以省略掉();

    7,)try{}catch{}finally{} catch中的处理可以使用case来区分不同的错误信息,针对不同的错误类型做出不同的日志记录等处理;

    8,)def main(args: Array[String]): Unit中,参数是一个字符数组,参数个的格式就是这样传递的;

    9,)参数传递支持多个参数,同时也支持多个参数返回。

    传递多参数,返回多参数示例:

    package com.dtgroup.study
    
    object HelloStduy {
      def main(args: Array[String]): Unit = {
        println("Hello Scala")
        var result0 = returnWithSomething("1111", 1)
        println(result0._1)
        //    for (item <- result0._2) println(item)
        println(result0._2.mkString(","))
        var result1 = returnWithSomething("mmmmm", 1)
    
        println(result1._1)
        //    for(item <- result1._2) println(item)
        println(result1._2.mkString(","))
      }
    
      def returnWithSomething(arg0: String, arg1: Int*): (Int, Array[String]) = {
        var result0 = 0
        var result1 = new Array[String](11)
    
        for (i <- 0 to 10) result1(i) = (i + 1).toString()
    
        try {
          result0 = arg0.toInt
        } catch {
          case e: Exception => {
            result0 = 2
            println("Fail convert to int")
          }
        } finally {
    
        }
    
        (result0, result1)
      }
    }

    输出结果:

    Hello Scala
    1111
    1,2,3,4,5,6,7,8,9,10,11
    Fail convert to int
    2
    1,2,3,4,5,6,7,8,9,10,11

  • 相关阅读:
    5.3二叉树的运算
    hadoop namenode切换
    org.apache.hadoop.security.AccessControlException
    Hive中的日志
    命令大全详解
    python深浅copy
    awk命令
    head&tail命令
    cut命令
    理解inode
  • 原文地址:https://www.cnblogs.com/yy3b2007com/p/4968735.html
Copyright © 2011-2022 走看看