www1350 / javaweb

http://www1350.github.io/
31 stars 5 forks source link

scala 学习(三) #39

Open www1350 opened 8 years ago

www1350 commented 8 years ago

List

val numbers = List(1, 2, 3, 4)
1::2::3::4

set

Set(1,2,3)

Seq

scala> Seq(1, 1, 2)
res3: Seq[Int] = List(1, 1, 2)

Tuple

val hostPort = ("localhost", 80)

hostPort._1
hostPort._2

hostPort match {
  case ("localhost", port) => ...
  case (host, port) => ...
}

scala> val h2 = "localhost"->80
h2: (String, Int) = (localhost,80)

scala> h2._1
res35: String = localhost

scala> h2._2
res36: Int = 80

scala> val (host,port) = h2
host: String = localhost
port: Int = 80
val t = (1 , 3.3 , "ews")
val value = t._2//get
val (fir ,sec , thir) = t
val (fir ,sec , _) = t//第三个不需要
"New York" .partition( _.isUpper)//("NY","ew ork")

map

//不可变
val scores = Map( "alice" -> 10 , "Bob" -> 3)
val scores = Map( ("alice" ,10) , ("Bob" , 3))
//可变
val scores = scala.collection.mutable.Map("alice" -> 10 , "Bob" -> 3)
val scores = scala.collection.mutable.HashMap[String , Int ]

//获取值
scores("Bob")
scores.getOrElse("Bob" , 0)
//set(可变)
scores("Bob") = 10
score += ("Bob"->10,"Fred" ->7)
for ((k,v) <- scores) //处理

方法

Traversable

下面所有方法在子类中都是可用的。参数和返回值的类型可能会因为子类的覆盖而看起来不同。

def head : A
def tail : Traversable[A]

这里是函数组合子定义的地方。

def map [B] (f: (A) => B) : CC[B]

返回每个元素都被 f 转化的集合

def foreach[U](f: Elem => U): Unit

在集合中的每个元素上执行 f 。

def find (p: (A) => Boolean) : Option[A]

返回匹配谓词函数的第一个元素

def filter (p: (A) => Boolean) : Traversable[A]

返回所有匹配谓词函数的元素集合

划分:

def partition (p: (A) ⇒ Boolean) : (Traversable[A], Traversable[A])

按照谓词函数把一个集合分割成两部分

def groupBy [K] (f: (A) => K) : Map[K, Traversable[A]]

转换:

有趣的是,你可以转换集合类型。

def toArray : Array[A]
def toArray [B >: A] (implicit arg0: ClassManifest[B]) : Array[B]
def toBuffer [B >: A] : Buffer[B]
def toIndexedSeq [B >: A] : IndexedSeq[B]
def toIterable : Iterable[A]
def toIterator : Iterator[A]
def toList : List[A]
def toMap [T, U] (implicit ev: <:<[A, (T, U)]) : Map[T, U]
def toSeq : Seq[A]
def toSet [B >: A] : Set[B]
def toStream : Stream[A]
def toString () : String
def toTraversable : Traversable[A]

把映射转换为一个数组,您会得到一个键值对的数组。

scala> Map(1 -> 2).toArray
res41: Array[(Int, Int)] = Array((1,2))

与Java

import scala.collection.JavaConverters._
   val sl = new scala.collection.mutable.ListBuffer[Int]
   val jl : java.util.List[Int] = sl.asJava
   val sl2 : scala.collection.mutable.Buffer[Int] = jl.asScala
   assert(sl eq sl2)

双向转换:

scala.collection.Iterable <=> java.lang.Iterable
scala.collection.Iterable <=> java.util.Collection
scala.collection.Iterator <=> java.util.{ Iterator, Enumeration }
scala.collection.mutable.Buffer <=> java.util.List
scala.collection.mutable.Set <=> java.util.Set
scala.collection.mutable.Map <=> java.util.{ Map, Dictionary }
scala.collection.mutable.ConcurrentMap <=> java.util.concurrent.ConcurrentMap

此外,也提供了以下单向转换

scala.collection.Seq => java.util.List
scala.collection.mutable.Seq => java.util.List
scala.collection.Set => java.util.Set
scala.collection.Map => java.util.Map

选项 Option

Option 是一个表示有可能包含值的容器。 Option基本的接口是这样的:

trait Option[T] {
  def isDefined: Boolean
  def get: T
  def getOrElse(t: T): T
}

Write

var username: Option[String] = None
...
username = Some("foobar")

instead of

var username: String = null
...
username = "foobar"

write

opt foreach { value =>
  operate(value)
}

instead of

if (opt.isDefined)
  operate(opt.get)
val result = res1 match {
  case Some(n) => n * 2
  case None => 0
}

拉链操作

val sys = Array( "<" , "-" , ">" )
val cos = Array( 2 , 10 , 2 )
val pairs = sys.zip(cos)
//结果 Array( ("<",2) , ("-",10) , (">",2) )

//getter/setter age= / age_=

私有字段,但是如下,Counter对象之间可以互相访问

class Counter {
 private var value = 0
 def increment() { value += 1 }
 def isLess( other : Counter ) = value < other.value
}

如果想要完全变成只能访问本对象

private[this] var value= 0

Bean 属性

class Person{
@BeanProperty var name : String = _
}

主构造

class Person( val name :String ,val age : Int){}

class Person( val name :String ="" ,private val age : Int = 0)

抽象类

abstract class Shape {
       def getArea():Int    // subclass should define this
}

特质(Traits)

trait Car {
  val brand: String
}

class BMW extends Car {
  val brand = "BMW"
}

通过with关键字,一个类可以扩展多个特质:

class BMW extends Car with Shiny {
  val brand = "BMW"
  val shineRefraction = 12
}

特质是可以有实现的

trait ConsoleLogger{
def log(msg:String)=println(msg)
}

class ALogger extends ConsoleLogger

scala> val a = new ALogger
a: ALogger = ALogger@32193528

scala> a.log("1")
1
trait Cache[K, V] {
  def get(key: K): V
  def put(key: K, value: V)
  def delete(key: K)
}

对象

也叫单例对象,单例对象用于持有一个类的唯一实例。通常用于工厂模式

object Timer {
  var count = 0

  def currentCount(): Long = {
    count += 1
    count
  }
}
class Student(name:String)
object Student{
def apply(name:String) = new Student(name)
}

scala> Student("2")
res26: Student = Student@290ad6a9