scala(12)A Tour of Scala: Upper Type Bounds

scala(12)A Tour of Scala: Upper Type Bounds

InMutableList
head - return the first element of the List
tail    - return the rest of the List

  def main(args: Array[String]): Unit = {
    var l1 = List(1,3,5,7)
    println(l1.head + " " + l1.tail) //1 List(3,5,7)
  }

Upper Type Bounds
An upper type bound T <: A  declares that type variable T refers to a subtype of type A.
trait Similar {
  def isSimilar(x: Any): Boolean
}


case class MyInt(x: Int) extends Similar {
  def isSimilar(m: Any): Boolean = {
    m.isInstanceOf[MyInt] && m.asInstanceOf[MyInt].x == x
  }
}


object ListUpperTypeBound {


  def findSimilar[T <: Similar](e: T, xs: List[T]): Boolean = {
    if (xs.isEmpty) false
    else if (e.isSimilar(xs.head)) true
    else findSimilar[T](e, xs.tail)
  }


  def main(args: Array[String]): Unit = {
    var l1 = List(1, 3, 5, 7)
    println(l1.head + " " + l1.tail) //1 List(3,5,7)


    val list: List[MyInt] = List(MyInt(1), MyInt(2), MyInt(3))
    println(findSimilar[MyInt](MyInt(4), list))  //false
    println(findSimilar[MyInt](MyInt(2), list))  //true
  }


}

Lower Type Bounds
The term T >: A

Tips: Recall Some Old Scala Syntax
Array()
List()  Manipulate the List()  list1:::list2, 13::list1, list1.::(13), Remember the differences among :::, ::, .::
(1,2,3) Tuple
Set()  Manipulate the Set      set1 += 3, the operator is +=
HashSet()     Manipulate the HashSet   hashSet1.+=(5)   .+=
Map()           Manipulate the Map map1.+=("4" -> "1000")

For Statement
for(file <- files)        for(file <- files if (file.getName.endsWith("bin"))  )
for(
     file <- files
     if(file.isFile)
     if(file.getName.endsWith("gitignore"))
)

val array_files = for (file <- files if(file.isFile)) yield file

parameter match {
     case "1" =>
          …
     case "2" =>
          …
     case _ =>
          ….
}

def speed(distance: Double, time: Double) = distance / time
val a = speed(distance = 100, time = 9)
Magic Collection Function List()    list1.exists((n:Int) => n >0), list1.exists(_%2 == 0)   list1.count(_>2)
                                                  list1.filter(_>0)
Generic Classes    Stack[T]

class Point(xc:Int, yc:Int) extends Similarity {}
flatMap will flat the results into the original list.

References:
http://www.scala-lang.org/node/136
http://www.scala-lang.org/node/137

http://www.scala-lang.org/api/current/index.html#scala.collection.mutable.MutableList

scala 2 ~ 11
scala(2) http://sillycat.iteye.com/blog/1536386
scala(3) http://sillycat.iteye.com/blog/1536391
scala(4) http://sillycat.iteye.com/blog/1536392
scala(5) http://sillycat.iteye.com/blog/1735124
scala(6) http://sillycat.iteye.com/blog/1748794
scala(7) http://sillycat.iteye.com/blog/1748937
scala(8) http://sillycat.iteye.com/blog/1775456
scala(9) http://sillycat.iteye.com/blog/1775972
scala(10) http://sillycat.iteye.com/blog/1775984
scala(11) http://sillycat.iteye.com/blog/1821490

你可能感兴趣的:(scala)