Scala学习-语言基础 - webdancer's Blog

Scala学习-语言基础

webdancer posted @ 2014年1月03日 16:14 in 编程语言 with tags scala , 1564 阅读

1.Scala解释器:键入scala命令启动,使用和python的差不多;也可以运行脚本文件:

 scala xx.scala

2.变量定义:两种变量类型:val和var,val类型变量一旦初始化,不能再被赋值,相当于java中的final类型的变量。与java不同的是Scala可以进行类型推导,不用显示的写出变量的类型。

var a = "Hello World"
val b = 3.14

如同想要显示的写出变量类型,可以在变量名称后面加上“:type”:

var a:String = "Hello World"
val b:Int = 3.14

3.函数定义:

 scala的函数定义用"def"作为开始的标识符,

def max(a:Int, b:Int):Int = {
    if (a>b)
        a
    else
        b
}

需要注意:函数的返回值在非递归函数时可以省去,但是作为良好的编程习惯,还是加上;在只有一个语句的情况下,大括号可以省略。

def error = println("Error!")

Scala的函数参数传递方式一般是CBV(call by value),如果参数类型前面有“=>”则使用CBN(call by name)。

4.控制结构:可以用while进行循环,if进行判断,与java一样的。

5.使用foreach和for来进行迭代:

函数时first citizen,可以充当参数,所以foreach的参数可以是function literal。例如如果输出脚本的参数,

args.foreach((arg:String) => println(arg))

也可以使用for,

for(arg <- args)
    println(arg)
Gujarat STD-4 Model 说:
2022年9月11日 23:39

GSEB STD-4 Model Paper 2023 Pdf Download for Gujarat State Elementary Level Primary School 4th Class Question Paper Pdf with Answers for Gujarati Medium, Hindi Medium, English Medium & Urdu Medium Students of Gandhinagar Board at Gujarat STD-4 Model Paper. Subject experts of the state and teaching staff of private schools have prepared and suggested the GSEB STD-4 Model Paper 2023 Pdf for Part-A, Part-B, Part-C and Part-D exams. Set wide solved question paper suggested as Gujarat Board 4th Class Model Paper 2023.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee