AzkaBan  
1. 循环

9*9乘法表 
for(i <- 1 to 9 ; j <- 1 to 9){            scala> for(i <- 1 to 10) yield i	
if(j==9) println(i*j)                          Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
else print(i*j+" ")                            直接构建集合
}

for(i <- 0 until (b.length,2)) print(b(i))    跳跃遍历
for(i <- (0 until b.length).reverse) print(b(i))  反向遍历
scala> val a3 = for(b <- b if b%2 ==0) yield b*b

var firstNg = true
val storeIndex = for(i <- 0 until a.length if firstNg || a(i)>=0 ) yield{if(a(i)<0) firstNg=false;i}


//遍历Map
for((key,value) <- ages) println(key + " " + value)
for(key <- ages.keySet) println(key)


2. 类

class HelloWorld{
	@BeanProperty var name:String=_           //生成类似java的getter setter方法。
}

1.用var定义变量,自动生成getter setter方法  调用时为 helloWorld.name helloWorld.name_="lei"
1.1 但是用private修饰后,其方法也会变为私有。
2.用val定义变量,只生成getter方法。因为val定义的值,只能被赋值一次,不可修改。

// object的功能其实和class类似,除了不能定义接受参数的constructor之外
// object也可以继承抽象类,并覆盖抽象类中的方法
//apply函数    通常在伴生对象中实现apply方法,并在其中实现构造伴生类的对象的功能

class Person(val name: String)

object Person {
  def apply(name: String) = new Person(name)
}


3. 函数式编程

// Scala的语法规定,将函数赋值给变量时,必须在函数后面加上空格和下划线

def sayHello(name: String) { println("Hello, " + name) }
val sayHelloFunc = sayHello _

//高阶函数    向函数中传入函数(匿名函数)
val sayHello = (name:String) => println("HELLO"+name)     //返回值为Unit


4. 内置函数

// sortWith: 对元素进行两两相比,进行排序
Array(3, 2, 5, 4, 10, 1).sortWith(_ < _)

List("Hello World", "You Me").flatMap(_.split(" "))

val line01 = scala.io.Source.fromFile("D://test1.txt").mkString


5. 模式匹配

def judgeGrade(name:String,grade:String){
	grade match{
		case "A" => print("excellent")
		case _ if name=="leo" => print(name+" is a goodboy come on")
		case _ grade => print("uh.... your grade is "+ _grade)    // _占位符
	}
}

//list 非常特殊  需要::连接各元素
def greeting(list:List[String]){
	list match{
		case "leo" :: "lilei" :: Nil => print("leo"+"lilei")
		case "leo" :: tail => print("leo and friends")
		case _ => print("who are you ?")
	}
}

//判断是否为空值
def getGrade(name:String){
	val grade = grades.get(name)
	grade match{
		case Some(grade) => print("can find your grade "+grade)
		case None => print("Nil")
	}
}


6. 泛型

//泛型函数
def getCard[T](content: T) = {
  if(content.isInstanceOf[Int]) "card: 001, " + content
  else if(content.isInstanceOf[String]) "card: this is your card, " + content
  else "card: " + content
}

//上边界 :  必须是该类 或该类的子类       [T <: Persion]
//下边界 [T >: Persion]           范围边界 [T <% Person] 必须与Person类有关系


//隐式转换
implicit def dog2person(dog: Object): Person = if(dog.isInstanceOf[Dog]) {val _dog = dog.asInstanceOf[Dog]; new Person(_dog.name) } else Nil


class TestComparator[T:Ordering](a:T,b:T){
  def bigger(implicit ord:Ordering[T]): Int ={
    ord.compare(a,b)
  }
}


val compare = new TestComparator[Int](3,2)
    print(compare.bigger)




/**要想实例化泛型数组,必须使用Manifest*/       manifest 显示的
def packageClass[T:Manifest](food:T*)={              //T* 变长参数
	val arr = new Array[T](food.length)				 //创建数组 将变长参数传入数组
	for(i <- 0 until food.length)arr(i)=food(i)
	arr												 //返回一个包含同类的多个对象的数组
}

//协变[+T] 子类都可进入
//逆变[-T] 只有父类可进入

//asInstanceOf强制转换类型
  


7. 注意事项

在泛型中,Object 包含 AnyVal 值类型(1) 与 AnyRef 引用类型("1")

ClassTag宏, 防止类型擦除;
class add[T:ClassTag](list: Int*){
  for(l <- list)
    println(l)
}

在集合中非scala.collections.Mutable 类型集合 无法更新集合内的数值,  只有可变集合可以 inplace更改, ListBuffer[T];

加强版冒泡排序:  for中 until 与 to 的不同
for (i <- low until high; j <- (low to i).reverse if j > low && compare(dest(j),dest(j-1)) <0 ){
  swap(dest,j,j-1)
}


IndexOutOfBoundsException, 一定要注意 (low, high)最后项:  if(q>=high || p < middle && compare(src(p),src(q))<0 )

 

//ClassTag 类标签 用于保留集合的类型, 构建数组或集合
def mkArray[T:ClassTag](elem:T*)=Array[T](elem:_*)



object TestWithScope {
    def withScope(func: => String) = {
        println("withscope")
        func
    }

    def bar(foo: String) = withScope {
        println("Bar: " + foo)
        "BBBB"
    }

    def main(args: Array[String]): Unit = {
        println(bar("AAAA"));
    }
}

  

枚举类

object Consistent extends Enumeration with Serializable {
  type Consistent = Value

  val prod:Value = Value("1")
  val stg:Value = Value("2")

  val s3_blms:Value = Value("3")

}

  

 

posted on 2019-05-25 16:59  AzkaBan  阅读(285)  评论(0编辑  收藏  举报