• 赋值语句无返回值
  • List
  • Option Some None
  • 抽象类和特质Trait
  • Concrete Mutable Collection Classes
    • List Buffers
    • StringBuilders
    • Linked Lists
    • Array Sequences
    • Array Stacks
  • public是Scala的默认访问级别

  • Scala里方法参数都是val,不是var。

  • 定义方法的时候加上等号是一个严谨的作风。不加等号放回Unit结果类型,可能会把实际所返回的结果掩盖。

  • 把操作符放在行尾而不是行头。

  • 除了String归于java.lang包之外,其余所有的基本类型都是包scala的成员。如scala.Int\scala.Char,位于scala包下面的所有类都被自动导入。

  • scala基本数据类型的长度和java是一样的。

  • 主构造器定义先决条件:require(arg);参数为布尔类型,用于保障构造对象之前数据的正确性。

  • 流间(mid-stream)变量绑定:for控制语句小括号中变量不用申明。

  • 制造新集合:for(子句)yield{循环体}

  • 捕获catch异常的书写方式和java不一样。

  //结果分别是2、1def f(): Int = try{return 1}finally{return 2}println(f());def g(): Int = try{1}finally{2}println(g());
  • match类似于java的switch,case中默认不是*而是下划线_。break关键字是默认存在的。match表达式也能产生值(返回值)。

  • 没有break和continue。

  • 占位符:下划线。代表参数。

  • 偏函数

  • 尾递归:最后一个动作调用自己的函数。

  • 函数可以作为其他函数的参数。参数书写形式为:函数A的引用名字:(A的参数)

  //该函数的参数是一个方法字面量,这个“参数方法”有一个Book类型的参数,返回值的类型是AnyRef。def printBookList(info: Book => AnyRef): Unit ={for(book <- books){println(info(book));}
  • ++操作符连接两个数组。

  • Unit 但与java的void,表示空。

  • 基本数据类型Int、Char、Boolean等是abstract和final修饰的。

  • Any是所有类的父类AnyRef类是Any类的直接子类,是所有引用类的基类,所以AnyRef类似于java的Object类。scala.AnyVal是Any的直接子类,是所有基本类型的父类。

  • scala字符串字面值比较实用等号,而判断两个字符串是不是同一个“引用”使用eq方法或者ne方法。这个点和java是不一样的,因为Java使用equals比较两个字符串的字面量值。

  • scala中的Null类是java中null引用对象的类型,它是每个引用类,也即是说每个继承自AnyRef的类,的子类。所以不能把null值赋值给整数变量。

  • scala中Nothing是所有类型的子类,处于scala的类层级的最底端。

  • trait 就像是带有具体方法的java接口。不使用impliments关键字,而是extends和with关键字。

  • 特质堆叠:子特质的抽象方法里面可以调用super特质中的抽象方法。进行相应的操作。

  • 当new实例化一个类的时候,scala把这个类和所有它继承的类还有他的特质以线性的次序放在一起。(堆叠行为)

  • 引用某包下面的所有类使用下划线而不是java的星号。scala的引用import可以出现在任何地方。

  • scala的private和Java的private有一点不一样。前者严格一点。

  • scala中,protected只在定义了成员的类的子类中可以被访问。而java中还允许在同一个包的其他类中进行这种访问。

  • scala可以直接指定自己对其他某一个包的可见性,即使他是被private修饰的。

  • private[this]标记的定义能在包含了定义的同一个对象中被访问。它比private更加严格。

  比如:如果Navigator类中的speed方法被private[this]修饰,那么new Navigator().speed是不能编译通过的。
  • 单例对象没有任何子类。

  • 判断空列表:xs.isEmpty

  • 集合对象通过elements方法名产生iteractor枚举器。

  • 列表List相当于java中的链表,并且是不可变 的。

  • ListBuffer是可改变的链表,相当于java的LinkedList; ArrayBuffer相当于java的ArrayList

  • 集合的创建方式:val words = scala.collection.mutable.Set.empty[String]; 或者val words = scala.collection.mutable.Set[String]();

  • 定义变量var c: Float = _; 在scala中不可以随便省略“=_” 初始化器。如果省略,这将定义为抽象变量,而不是未初始化的变量。


赋值语句无返回值

在Scala中,赋值语句永远都返回unit值

var line = ""
while((line = readLine()) != ""){//
}
这时,你会收到编译器编译警告,Unit与String对比将永远返回true

不过,可以写成下面这样,只是这样没有函数式语言的风格了。

val reader = new BufferedReader(new FileReader(file))
var line = reader.readLine()
while(line != null){println(line)line = reader.readLine()
}

或者下面这样子,看起来舒服一点

for(line <- Source.fromFile(file).getLines()){println(line)
}

List

scala> val a = List(1)
a: List[Int] = List(1)scala> val b = List(2)
b: List[Int] = List(2)scala> val c = List(3)
c: List[Int] = List(3)
scala> val x = a +: b;
x: List[Any] = List(List(1), 2)scala> val x = a :+ b;
x: List[Any] = List(1, List(2))scala> val x = a :+ b :+ c;
x: List[Any] = List(1, List(2), List(3))
scala> val x = a ++: b
x: List[Int] = List(1, 2)scala> val x = a ++: b ++: c;
x: List[Int] = List(1, 2, 3)
scala> val x = a :++ b;
<console>:10: error: value :++ is not a member of List[Int]val x = a :++ b;^
scala> 

构造函数:

class Data (aPhoneNum:String, aBaseID:String,aTime:String, aLongitude:String, aLatitude:String){@BeanPropertyvar phoneNum:String =aPhoneNum@BeanPropertyval baseID:String = aBaseID@BeanPropertyval time:String = aTime@BeanPropertyval longitude:String = aLongitude@BeanPropertyval latitude:String = aLatitude}object Data{def apply(phoneNum:String,baseID:String, time:String,longitude:String, latitude:String): Data = new Data(phoneNum, baseID, time, longitude, latitude)
}object Test{def main(args: Array[String]): Unit = {val data = Data("a","b","c","d","e")data.phoneNum = "df"println(data.phoneNum)}
}

Option Some None

Some和None都是Option抽象类的子类。这两个子类都是被case和object修饰的类。它们存在的目的是消除java代码中大量存在的null关键字。下面是对Some和None的测试:

import org.junit.{Assert, Test}/*** Created by liangyh on 2/21/17.*/
@Test
class SomeAndNoneTest extends Assert{@Testdef testSome(): Unit ={Assert.assertTrue(Some(1) == Some(1))Assert.assertFalse(Some(1) == Some)Assert.assertTrue(Some == Some)val some1 = Some(Data("h",1))val some2 = Some(Data("h",1))Assert.assertFalse(some1 == some2)Assert.assertTrue(some1 != None)}class Data(name:String, age:Int){def print(): Unit ={println(name +", "+age)}}object Data{def apply(name: String, age: Int): Data = new Data(name, age)}
}

抽象类和特质Trait

和java不同的地方在于scala的接口不叫接口,而是叫特质,实现一个接口使用的关键字不是implements,而是extends和with。如果只有一个特质,使用extends;如果有两个或者两个以上特质,使用extends和with,而且extends用一次,with对应一个特质使用一次,如下面代码所示。而with不能使用在抽象类上面。所以,对于一个抽象类和多个特质的情况,需要使用extends继承抽象类,使用with实现特质。

/*** Created by liangyh on 2/22/17.*/class TraitTest extends MyAbstract with MyTrait with MyTrait2{override def say(words: String): Unit = {println(words)}override def eat(): Unit ={println("eat")}override def say2(words: String): Unit = {println(words)}
}object TraitTest{def main(args: Array[String]): Unit = {val test = new TraitTest()test.eat()test.say("hello world")test.doWork()}
}abstract class MyAbstract{def eat()def doWork(): Unit ={println("do work")}
}trait MyTrait{def say(words:String)
}trait MyTrait2{def say2(words:String)
}

Concrete Mutable Collection Classes

You’ve now seen the most commonly used immutable collection classes that Scala provides in its standard library. Take a look now at the mutable collection classes.
Array Buffers

An ArrayBuffer buffer holds an array and a size. Most operations on an array buffer have the same speed as for an array, because the operations simply access and modify the underlying array. Additionally, array buffers can have data efficiently added to the end. Appending an item to an array buffer takes amortized constant time. Thus, array buffers are useful for efficiently building up a large collection whenever the new items are always added to the end.

scala> val buf = scala.collection.mutable.ArrayBuffer.empty[Int]
buf: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
scala> buf += 1
res32: buf.type = ArrayBuffer(1)
scala> buf += 10
res33: buf.type = ArrayBuffer(1, 10)
scala> buf.toArray
res34: Array[Int] = Array(1, 10)

List Buffers

A ListBuffer is like an array buffer except that it uses a linked list internally instead of an array. If you plan to convert the buffer to a list once it is built up, use a list buffer instead of an array buffer.

scala> val buf = scala.collection.mutable.ListBuffer.empty[Int]
buf: scala.collection.mutable.ListBuffer[Int] = ListBuffer()
scala> buf += 1
res35: buf.type = ListBuffer(1)
scala> buf += 10
res36: buf.type = ListBuffer(1, 10)
scala> buf.toList
res37: List[Int] = List(1, 10)

StringBuilders

Just like an array buffer is useful for building arrays, and a list buffer is useful for building lists, a StringBuilder is useful for building strings. String builders are so commonly used that they are already imported into the default namespace. Create them with a simple new StringBuilder, like this:

scala> val buf = new StringBuilder
buf: StringBuilder =
scala> buf += 'a'
res38: buf.type = a
scala> buf ++= "bcdef"
res39: buf.type = abcdef
scala> buf.toString
res41: String = abcdef

Linked Lists

Linked lists are mutable sequences that consist of nodes which are linked with next pointers. They are supported by class LinkedList. In most languages null would be picked as the empty linked list. That does not work for Scala collections, because even empty sequences must support all sequence methods. In particular LinkedList.empty.isEmpty should return true and not throw a NullPointerException. Empty linked lists are encoded instead in a special way: Their next field points back to the node itself. Like their immutable cousins, linked lists are best traversed sequentially. In addition linked lists make it easy to insert an element or linked list into another linked list.
Double Linked Lists

Double linked lists are like single linked lists, except that they have besides next another mutable field prev that points to the element preceding the current node. The main benefit of that additional link is that it makes element removal very fast. Double linked lists are supported by class DoubleLinkedList.
Mutable Lists

A MutableList consists of a single linked list together with a pointer that refers to the terminal empty node of that list. This makes list append a constant time operation because it avoids having to traverse the list in search for its terminal node. MutableList is currently the standard implementation of mutable.LinearSeq in Scala.
Queues

Scala provides mutable queues in addition to immutable ones. You use a mQueue similarly to how you use an immutable one, but instead of enqueue, you use the += and ++= operators to append. Also, on a mutable queue, the dequeue method will just remove the head element from the queue and return it. Here’s an example:

scala> val queue = new scala.collection.mutable.Queue[String]
queue: scala.collection.mutable.Queue[String] = Queue()
scala> queue += "a"
res10: queue.type = Queue(a)
scala> queue ++= List("b", "c")
res11: queue.type = Queue(a, b, c)
scala> queue
res12: scala.collection.mutable.Queue[String] = Queue(a, b, c)
scala> queue.dequeue
res13: String = a
scala> queue
res14: scala.collection.mutable.Queue[String] = Queue(b, c)

Array Sequences

Array sequences are mutable sequences of fixed size which store their elements internally in an Array[Object]. They are implemented in Scala by class ArraySeq.

You would typically use an ArraySeq if you want an array for its performance characteristics, but you also want to create generic instances of the sequence where you do not know the type of the elements and you do not have a ClassManifest to provide it at run-time. These issues are explained in the section on arrays.
Stacks

You saw immutable stacks earlier. There is also a mutable version, supported by class mutable.Stack. It works exactly the same as the immutable version except that modifications happen in place.

scala> val stack = new scala.collection.mutable.Stack[Int]
stack: scala.collection.mutable.Stack[Int] = Stack()
scala> stack.push(1)
res0: stack.type = Stack(1)
scala> stack
res1: scala.collection.mutable.Stack[Int] = Stack(1)
scala> stack.push(2)
res0: stack.type = Stack(1, 2)
scala> stack
res3: scala.collection.mutable.Stack[Int] = Stack(1, 2)
scala> stack.top
res8: Int = 2
scala> stack
res9: scala.collection.mutable.Stack[Int] = Stack(1, 2)
scala> stack.pop
res10: Int = 2
scala> stack
res11: scala.collection.mutable.Stack[Int] = Stack(1)

Array Stacks

ArrayStack is an alternative implementation of a mutable stack which is backed by an Array that gets re-sized as needed. It provides fast indexing and is generally slightly more efficient for most operations than a normal mutable stack.
Hash Tables

A hash table stores its elements in an underlying array, placing each item at a position in the array determined by the hash code of that item. Adding an element to a hash table takes only constant time, so long as there isn’t already another element in the array that has the same hash code. Hash tables are thus very fast so long as the objects placed in them have a good distribution of hash codes. As a result, the default mutable map and set types in Scala are based on hash tables. You can access them also directly under the names mutable.HashSet and mutable.HashMap.

Hash sets and maps are used just like any other set or map. Here are some simple examples:

    scala> val map = scala.collection.mutable.HashMap.empty[Int,String]map: scala.collection.mutable.HashMap[Int,String] = Map()scala> map += (1 -> "make a web site")res42: map.type = Map(1 -> make a web site)scala> map += (3 -> "profit!")res43: map.type = Map(1 -> make a web site, 3 -> profit!)scala> map(1)res44: String = make a web sitescala> map contains 2res46: Boolean = false

Iteration over a hash table is not guaranteed to occur in any particular order. Iteration simply proceeds through the underlying array in whichever order it happens to be in. To get a guaranteed iteration order, use a linked hash map or set instead of a regular one. A linked hash map or set is just like a regular hash map or set except that it also includes a linked list of the elements in the order they were added. Iteration over such a collection is always in the same order that the elements were initially added.
Weak Hash Maps

A weak hash map is a special kind of hash map where the garbage collector does not follow links from the map to the keys stored in it. This means that a key and its associated value will disappear from the map if there is no other reference to that key. Weak hash maps are useful for tasks such as caching, where you want to re-use an expensive function’s result if the function is called again on the same key. If keys and function results are stored in a regular hash map, the map could grow without bounds, and no key would ever become garbage. Using a weak hash map avoids this problem. As soon as a key object becomes unreachable, it’s entry is removed from the weak hashmap. Weak hash maps in Scala are implemented by class WeakHashMap as a wrapper of an underlying Java implementation java.util.WeakHashMap.
Concurrent Maps

A concurrent map can be accessed by several threads at once. In addition to the usual Map operations, it provides the following atomic operations:
Operations in class ConcurrentMap
WHAT IT IS WHAT IT DOES
m putIfAbsent(k, v) Adds key/value binding k -> v unless k is already defined in m
m remove (k, v) Removes entry for k if it is currently mapped to v.
m replace (k, old, new) Replaces value associated with key k to new, if it was previously bound to old.
m replace (k, v) Replaces value associated with key k to v, if it was previously bound to some value.

ConcurrentMap is a trait in the Scala collections library. Currently, its only implementation is Java’s java.util.concurrent.ConcurrentMap, which can be converted automatically into a Scala map using the standard Java/Scala collection conversions.
Mutable Bitsets

A mutable bit of type mutable.BitSet set is just like an immutable one, except that it is modified in place. Mutable bit sets are slightly more efficient at updating than immutable ones, because they don’t have to copy around Longs that haven’t changed.

    scala> val bits = scala.collection.mutable.BitSet.emptybits: scala.collection.mutable.BitSet = BitSet()scala> bits += 1res49: bits.type = BitSet(1)scala> bits += 3res50: bits.type = BitSet(1, 3)scala> bitsres51: scala.collection.mutable.BitSet = BitSet(1, 3)

scala-doc-collection

effectivescala

scala-school

origins-of-scala

Ninety-Nine Scala Problems

Scala Programming相关推荐

  1. 018 The Scala Programming Language

    1.Scala介绍 Scala(百度百科) 为什么要学习Scala 为什么要使用 Scala 语言?Scala 语言的优势在哪里? 为什么选择Scala,它在大数据处理方面有何优势? 博主学习Scal ...

  2. gitter 卸载_最佳Gitter频道:Scala

    gitter 卸载 by Gitter 通过吉特 最佳Gitter频道:Scala (Best Gitter channels on: Scala) Scala is an object-orient ...

  3. 【开发工具】SCALA

    Scala是一门多范式的编程语言,一种类似java的编程语言 [1] ,设计初衷是实现可伸缩的语言 [2] .并集成面向对象编程和函数式编程的各种特性. Scala编程语言抓住了很多开发者的眼球.如果 ...

  4. scala中抽象类_Scala中的抽象类

    scala中抽象类 抽象类 (Abstract Class) In the Scala programming language, abstraction is achieved using abst ...

  5. scala部分应用函数_Scala中的部分函数

    scala部分应用函数 Scala部分功能 (Scala partial functions) A partial function is a function that returns values ...

  6. scala 函数中嵌套函数_Scala合成函数

    scala 函数中嵌套函数 Scala中的合成功能 (Composition function in Scala) Scala composition function is a way in whi ...

  7. scala字符替换_如何替换Scala中的“坏”字符?

    scala字符替换 In Scala, programming language, all sorts of special characters are valid. The character s ...

  8. scala中命名参数函数_Scala中带有命名参数的函数

    scala中命名参数函数 具有命名参数的函数 (Functions with named arguments ) A function is Scala can take multiple argum ...

  9. scala 随机生成整数_如何在Scala中以整数形式获取当前年份?

    scala 随机生成整数 In Scala programming language, there is an option for the programmer to use libraries o ...

最新文章

  1. JVM GC参数以及GC算法的应用
  2. html5 coverflow,使用FancyCoverFlow实现3D无限循环切换视图
  3. CentOS 5 上安装git
  4. ren命令linux,Linux mren命令
  5. C#中配置文件保存的路径
  6. Servlet学习的两个案例之网站访问次数的统计
  7. Web — 选择器+浮动+清除
  8. 机器学习数学基础:学习线性代数,千万不要误入歧途!推荐一个正确学习路线
  9. 详解30道Vue面试题
  10. linux下ftp工具
  11. html语言文本框怎么做,HTML文本框参考样式
  12. Texturepackage工具免费申请正版密钥
  13. gridsome(三)——plugins
  14. Python学习日志12 - 办公自动化
  15. UEStudio设置为传统菜单
  16. 学习Python之小练习(飞机大战)(1)
  17. 70张让你大开眼界的照片(配…
  18. 文科生,你为啥学编程?
  19. 渝粤题库 陕西师范大学 《中国法制史》作业
  20. 不知道你有没有听说过所谓编程知识也是有半衰期的?

热门文章

  1. war包解压不了_牛骨高汤的熬制方法,拿走不谢!有了这配方,还愁开不了小吃店?...
  2. 前端笔记(4)css,复合选择器,标签的显示模式,行高,css背景,css三大特性
  3. 有5个学生,4门课程,用子函数的方法显示平均分最高的学生的所有成绩
  4. Vmo前端数据模型设计
  5. Web API与JWT认证
  6. Alchemy环境的搭建
  7. 如何解决MySQL连接超时关闭
  8. ibatis.net私人学习资料,勿下(加密)
  9. 《Javascript入门学习全集》 Javascript学习第二季(实战4)
  10. 虚拟机磁盘类型_虚拟机存储类型分为哪些种类