从零开始学Scala系列(二)之初识Scala

来源:互联网 发布:超市销售量的数据 编辑:程序博客网 时间:2024/06/11 06:10

1. 学习使用scala解释器

C:\Users\rodbate>scalaWelcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).Type in expressions for evaluation. Or try :help.scala> :help
  • 1
  • 2
  • 3
  • 4
  • 5

:help命令可查看命令帮助:

scala> :helpAll commands can be abbreviated, e.g., :he instead of :help.:edit <id>|<line>        edit history:help [command]          print this summary or command-specific help:history [num]           show the history (optional num is commands to show):h? <string>             search the history:imports [name name ...] show import history, identifying sources of names:implicits [-v]          show the implicits in scope:javap <path|class>      disassemble a file or class name:line <id>|<line>        place line(s) at the end of history:load <path>             interpret lines in a file:paste [-raw] [path]     enter paste mode or paste a file:power                   enable power user mode:quit                    exit the interpreter:replay [options]        reset the repl and replay all previous commands:require <path>          add a jar to the classpath:reset [options]         reset the repl to its initial state, forgetting all session entries:save <path>             save replayable session to a file:sh <command line>       run a shell command (result is implicitly => List[String]):settings <options>      update compiler options, if possible; see reset:silent                  disable/enable automatic printing of results:type [-v] <expr>        display the type of an expression without evaluating it:kind [-v] <expr>        display the kind of expression's type:warnings                show the suppressed warnings from the most recent line which had any
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

首先写个hello world 先啊!

scala> println("Hello World")Hello World
  • 1
  • 2

命令行表达式运算 比如 1 + 2

scala> 1 + 2res1: Int = 3
  • 1
  • 2
  • res1 用于保存表达式1+2的结果的变量 究竟是可变(var)类型 还是不可变(val)类型,做个试验试试:
scala> 1 + 2res1: Int = 3scala> println(res1)3scala> res1 = 2<console>:12: error: reassignment to val       res1 = 2scala> println(res1)3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

由此可知res1是val不可变的类型(不可重新赋值变量,相当于java中的final,C语言中的const修饰的变量)

res1: Int = 3 冒号是变量类型和变量之间的分隔符,再由于res1是不可变的, 可相当于java中的 final int res1 = 3

scala> res1 * 9res5: Int = 27
  • 1
  • 2

其实在scala中 + - * / % 这些运算符在scala也可以理解为函数(function) 后面细说。

2. scala中的变量种类

scala中的变量种类有两种var和val

  • val 不可变量,常量,不可重新赋值(相当于final)
  • var 可变量, 可重新赋值

看两个例子

scala> val str = "hello scala"str: String = hello scalascala> print(str)hello scalascala> str = "hello"<console>:12: error: reassignment to val       str = "hello"           ^
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
scala> var string = "hello scala"string: String = hello scalascala> println(string)hello scalascala> string = "changed"string: String = changedscala> println(string)changed
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这两个例子充分说明了 var 和 val两种变量的区别。

当然我们在scala中声明变量时,也可显示指定变量类型 如:

scala> val s: String = "scala"s: String = scalascala> val s1: java.lang.String = "java"s1: String = java
  • 1
  • 2
  • 3
  • 4
  • 5

和java中一样在java.lang包下的类可以直接使用简单类名引用,不需要全限定名,而且在scala中也多了一个这样包 就是scala包下的类和object的引用(后面用到细说)。

scala> val multiline =     | "multiline"multiline: String = multilinescala> val ss =     |     |You typed two blank lines.  Starting a new command.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

scala命令行中 多行连续可按一次enter,如果要结束多行状态,就需要连续按两次enter。

3 初始scala函数(Function)

说到scala,就会想起它的函数编程风格,那接下来就简单地来认识下scala函数吧。

  • 定义一个简单的max函数 输入两个值 求最大值
scala> def max(x: Int, y:Int): Int = {     |   if(x > y) x else y     | }max: (x: Int, y: Int)Intscala> println(max(1,2))2scala> println(max(10,2))10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这里写图片描述

当然上述函数还不是最简形式

scala> def max1(x: Int, y: Int) = if (x > y) x else ymax1: (x: Int, y: Int)Intscala> println(max1(1,10))10
  • 1
  • 2
  • 3
  • 4
  • 5

函数返回值类型可省略(但是最好显示声明,可读性好点), 函数体只有一行可省略大括号

  • 无返回值,无参数的函数
scala> def hello(): Unit = println("hello")hello: ()Unitscala> hellohelloscala> hello()hello
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

scala中无参函数调用可省略小括号。Unit返回值代表返回值为空 (如java中的void)

看下hello函数的最简形式

scala> def hello1 = println("hello1")hello1: Unitscala> hello1hello1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4. scala 脚本(script)

scala是支持脚本的。先创建一个hello.scala的文件并追加如下内容:

C:\Users\rodbate\Desktop>echo println("hello scala script!") >> hello.scalaC:\Users\rodbate\Desktop>scala hello.scalahello scala script!
  • 1
  • 2
  • 3
  • 4
  • 5

scala脚本还支持命令行传参数 args(0) 以0开始

C:\Users\rodbate\Desktop>echo println("hello " + args(0)) > args.scalaC:\Users\rodbate\Desktop>scala args.scala first secondhello first
  • 1
  • 2
  • 3
  • 4
  • 5

这一小节就到这了,下节再见。