前言
最近在工作中,使用python操作spark发现相关api不能很好的支持。另外加上,并不能很好的理解相关工作日志及参数。决定无论是否在项目中提出语言转型,只是为了参数调优与异常处理,也要把scala进行一次系统的入门。本批文章在知识的介绍下将与python做比较,希望能帮助到打算学习scala 的pythoner
scala 变量赋值
scala 可以通过两个保留字赋值
分别是val 和 var
val 初始化的值 无法改变,类似于js里的常量
var 初始化的值 则可以改变 就是变量
val 变量名:类型 = value
val age:Int = 20
类型可以省略
常量值不可变,变量则可以
scala 基本数据类型
字节类型 Byte/Char
数值类型 Short/Int/Long/Float/Double
布尔类型 true false
字符串类型 String
scala 类型转换
val money = 10.asInstanceOf[Double]
lazy
为了提升处理效率,scala在对常/变量进行声明时。如果是lazy的,声明时不会直接的进行赋值或者声明,而是会在真正的计算中声明。
函数的书写
第一个hello world 程序
老规矩,学习一门语言还是先hello world 一下
object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello World My first scala application")
}
}
函数的定义
def 方法名(参数1:参数类型,参数2:参数类型): 返回值类型 = {
函数体
返回值
}
def sum(age1:Int,age2:Int): Float = {
age1 + age2
}
如果函数无需传参,则直接定义即可
def second_value() = {
1 + 1
}
如果函数不需要返回值
def sayHello(name:String): Unit ={
println("Hello "+name)
}
参数的使用
和大多数其他语言一样,scala也可以使用默认参数,也就是函数的缺省值。
def main(args: Array[String]): Unit = {
println(sayName())
println(sayName("michael"))
}
def sayName(name:String="康康"):String = {
name
}
}
同样,像python一样scala可以通过参数名进行传参
animal_Information("dog",3)
animal_Information(age = 100,name = "gouxiong")
scala也支持可变参数,虽然并不像python那么灵活。
object function_study {
def add_sum(numbers:Int*):Int = {
var result = 0
for(number <- numbers){
result += number
}
result
}
}
条件表达式
compare_score(60,59)
compare_score(60,90)
def compare_score(score1:Int,score2:Int): Unit ={
val score = (score1+score2)/2
if(score>60){
println("及格")
} else {
println("不及格")
}
}
循环表达式
Range 函数
跟python很相似,他会生成一个左闭的数组,当然也能设置步长
除了Range函数外,scala 还有 to 与 unit 方法,不同于这两个函数是双闭区间,其实还是调用的Range方法
val animal_array = Array("dog","cat","pig","panda","money")
for (animal <- animal_array){
if(animal=="dog"){
println("wang wang")
} else {
println("other"+animal)
}
}
scala 还提供了另一种更优雅的写法 foreach 方法
animal_array.foreach(x => console_animal(x))
def console_animal(name:String): Unit ={
if(name=="dog"){
println("wang wang ")
}else {
println("other animal"+name)
}
}