之前的基本语法包括循环什么的就不写了,直接从定义函数开始。
一、定义函数
scala中定义函数需要定义函数的名字、参数和函数体。
def sayHello(name:String,age:Int) = {
if (age >= 18) {printf("hi, $s,u r bitch!!!\n",name);age}
else { printf("hi,%s,u r little bitch !!!",name); age
}
}
scala 要求给出所有参数的类型,但是不一定要求给出返回值的类型,前提是只要右侧的函数体中不包含递归的语句
def sayHello(name:String) = print("Hello",+name)
def sum(n:Int) = {
result = 0
for (i <- 1 to n) {
result += i
}
result
}
与之前函数不同的是,如果在函数体内递归调用函数自身,则必须手动给出函数的返回类型。
示例为斐波那契数列:
def fab(n:Int):Int = {
if (n <= 1 ) 1
else fab(n-1) + fab(n-2)
}
二、函数之默认参数和带名参数
示例:
def sayHello(firstname:String,middlename: String = "wiliam",lastname:String = "Bob")=print("hello" + " " + firstname + " " + middlename + " " + lastname)
sayHello("leo",lastname = "jack" ,middlename = "pp")
scala中可以混合使用未命名参数和带名参数,但是未命名参数必须排在带名参数前面。
三、函数之变长参数
在scala中,有时需要将函数定义为参数个数可变的形式,可以使用变长参数定义函数
示例代码:(注意,定义函数中如果没有“=”则无返回值)
def sum(nums:Int*) = {
var result = 0
for (num <- nums) result += num
result
}
如果想要将一个已有的序列直接调用变长参数函数,直接使用sum(1 to 5)不可行,此时使用scala特殊的语法将参数定义为序列
val s = sum(1 to 5: _*)
示例:使用递归函数实现累加
def sum2(nums: Int*):Int = {
if (nums.length == 0) 0
else nums.head + sum2(nums.tail: _*)
}
四、函数之 过程、lazy值、异常
示例:
def sayHello(name:String) = "hello " + name
def sayhello(name:String) {print("hello, " + name);"hello, " + name}
def sayhello(name:String): Unit = "hello, " + name
import scala.io.Source._
lazy val lines = fromFile("D://text.txt").mkString
示例:
try {
throw new IllegalArgumentException("illgal argument!!!")
} catch{
case _:IllegalArgumentException => print("sorry,error!")
} finally {
print("\nrelease io resourses!!!")
}
try {
throw new IllegalArgumentException("illgal argument!!!")
} catch{
case e1:IOException => println("io exception")
case e2:IllegalArgumentException => print("sorry,error!")
} finally {
print("\nrelease io resourses!!!")
}
一、数组操作值Array、ArrayBuffer以及遍历数组
val a = new Array[Int](10)
val a = new Array[String](10)
val a = Array("hello","world")
a(0) = "hi"
数组.length
可以返回数组长度
import scala.collection.mutable.ArrayBuffer
val b = ArrayBuffer[Int]()
b += 1
b += (2,3,4,5)
b ++= Array(6,7,8,9,10)
b.trimEnd(5)
b.insert(5,6)
b.insert(6,7,8,9,10)
b.remove(1)
b.remove(1,3)
b.toArray
a.toBuffer
for (i <- 0 until b.length) println(b(i))
for (i <- 0 until (b.length,2)) println(b(i))
for (i <- (0 until b.length).reverse) println(b(i))
for (e <- b) println(e)
数组元素求和
val a = Array(1,2,3,4,5)
val sum = a.sum
获取数组最大值
val max = a.max
对数组进行排序
scala.util.Sorting.quickSort(a)
获取数组中的所有元素内容
a.mkString
a.mkString(",")
a.mkString("(",",",")")
ArrayBuffer的toString与Array不太一样,主要区别在于“toString”
import scala.collection.mutable.ArrayBuffer
val b = ArrayBuffer[Int]()
b += (1,2,3,4,5)
b.toString
b.mkString
二、数组操作之数组转换
val a = Array(1,2,3,4,5)
val a2 = for(ele <- a) yield ele * ele
val b = ArrayBuffer[Int]()
b += (1,2,3,4,5)
val b2 = for(ele <- b) yield ele * ele
val a3 = for (ele <- a if ele % 2 == 0) yield ele * ele
a.filter(_ % 2 == 0).map(2 * _)
a.filter{_ % 2 == 0} map{2 * _}
val a = ArrayBuffer[Int]()
a += (1,2,3,4,5,-1,-3,-5,-9)
var foundFirstNegative = false
var arrayLength = a.length
var index = 0
while(index < arrayLength) {
if (a(index) >= 0) {
index += 1
} else {
if (!foundFirstNegative){foundFirstNegative = true;index += 1}
else{a.remove(index);arrayLength -= 1}
}
}
val a = ArrayBuffer[Int]()
a += (1,2,3,4,5,-1,-3,-5,-9)
var foundFirstNegative = false
val keepIndexes = for (i <- 0 until a.length if !foundFirstNegative || a(i) >= 0) yield{
if (a(i) < 0) foundFirstNegative = true
i
}
for (i <- 0 until keepIndexes.length){a(i) = a(keepIndexes(i))}
a.trimEnd(a.length - keepIndexes.length)
Map与Tuple
val age = Map("leo" -> 23,"jack" -> 34)
val age = Map(("leo",12),("jack",33))
val ages = scala.collection.mutable.Map("leo" -> 12,"mary" -> 25)
ages("leo") = 31
val ages = new.scala.collection.mutable.HashMap[String,Int]
val leoage = ages("leo") (如果key不存在,则报错)
使用contains函数检查是否存在
val leoage = if (ages.contains("leo")) ages("leo") else 0
getOrElse函数
val leoage = ages.getOrElse("leo",0)
更新Map的元素
ages("leo") = 31
增加多个元素
ages += ("mike" -> 34,"lucy" -> 35)
移除元素
ages -= "mike"
val ages2 = age + ("tom" -> 23,"bob" -> 26) (这里的age是不可变Map)
val ages3 = ages2 - "tom"
遍历Map的entrySet
for ((key,value) <- ages) println(key + " " + value)
遍历Map的key
for (key <- ages.keySet) println(key)
遍历Map的value
for (value <- ages.values) println(value)
生成新Map 反转key和value
for ((key,value) <- ages) yield (value,key)
val ages = scala.collection.immutable.SortedMap("leo" -> 30,"bob" -> 23)
Map的元素类型——Tuple
面向对象编程之类
class HelloWorld{
private var name = "leo"
def sayHello(){print("hello," + name)
def getname = name
}
class Student{
private var myName = "leo"
def name = "your name is " + myName
def name_=(newValue:String){
print("you cannot edit your name!")
}
}
class Student{
private var myName = "leo"
def updateName(newName:String){
if (newName == "leo1") myName = newName
else println("not accept this new name," + newName)
}
def name = myName
}
class Student{
private var myAge = 0
def age_=(newValue:Int){
if (newValue > 0) myAge = newValue
else print("illegal age!")
}
def age = myAge
def older(s:Student) = {
myAge > s.myAge
}
}
class Student{
private[this] var myAge = 0
def age_=(newValue:Int){
if(newValue > 0) myAge = newValue
else println("illegal age!")
}
def age = myAge
def older(s:Student) = {
myAge > s.myAge
}
}
import scala.beans.BeanProperty
class Student{
@BeanProperty var name:String = _
}
或者
class Student(@BeanProperty var name:String)
class Student{
private var name = ""
private var age = 0
def this(name:String){
this()
this.name = name
}
def this(name:String,age:Int){
this(name)
this.age = age
}
}
class Student(val name:String,val age:Int){
println("your name is "+ name +",your age is "+ age)
}
class Student(val name:String = "leo ",val age:Int = 30){
println("your name is "+ name +",your age is "+ age)
}
import scala.collection.mutable.ArrayBuffer
class Class{
class Student(val name:String)
val students = new ArrayBuffer[Student]()
def getStudent(name:String) = {
new Student(name)
}
}