scala入门


scala> "35, 36, 34, 39, 38, 42, 40, 22, 26, 27, 28, 29, 3, 1, 0, 5, 31, 58, 57, 56, 18, 15, 16, 13, 14, 11, 12, 21, 20, 61, 49, 48, 45, 10, 52, 50".split(", ").map(_.toInt).sorted

scala> val messages = (1 to 4).map{ x => println(x)}
1
2
3
4
messages: scala.collection.immutable.IndexedSeq[Unit] = Vector((), (), (), ())

scala> val messages = (1 to 4).map{ x => val s = (1 to 3).map(y => 3); println(s)}
Vector(3, 3, 3)
Vector(3, 3, 3)
Vector(3, 3, 3)
Vector(3, 3, 3)

  • 一些总结

类型使用[], 内容使用(), 例如: var s : Set[Int] = Set(1,3,5,7)

Array, Tuple可以new来构造,List, Map因为是abstract的,不能使用New来构造 , Map: 

HashSet和HashMap 的快速查找,这些集合的最常用的形式。 HashSet APIHashMap API

TreeMap 是SortedMap的一个子类,它可以让你进行有序访问。 TreeMap API

scala> import scala.collection.immutable.HashMap
import scala.collection.immutable.HashMap

scala> val m = new HashMap()
m: scala.collection.immutable.HashMap[Nothing,Nothing] = Map()

collections: List, Set, Map

Scala's Seq would be Java's List, Seq is a trait; and Scala's List would be Java's LinkedList,Scala's List is immutable, which is not the case of LinkedList,List is an abstract class that is extended by Nil and ::

http://stackoverflow.com/questions/10866639/scala-difference-between-a-seq-and-a-list

Iterable: A base trait for iterable collections. Iterator: Iterators are data structures that allow to iterate over a sequence of elements.

http://stackoverflow.com/questions/11302270/what-is-the-relation-between-iterable-and-iterator

  • 一些空类型: null, Nil, None

Null- Its a Trait.
null- Its an instance of Null- Similar to Java null.

Nil- Represents an emptry List of anything of zero length. Its not that it refers to nothing but it refers to List which has no contents.

Nothing is a Trait. Its a subtype of everything. But not superclass of anything. There are no instances of Nothing.

None- Used to represent a sensible return value. Just to avoid null pointer exception. Option has exactly 2 subclasses- Some and None. None signifies no result from the method.

Unit- Type of method that doesn’t return a value of anys sort.

Option[T]: Some[T] or None .  getOrElse

  •  一些操作

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

scala> val a = Sequence(1, 2)
warning: there were 1 deprecation warnings; re-run with -deprecation for details
a: Seq[Int] = List(1, 2)

An iterator is not a collection, but rather a way to access the elements of a collection one by one, it.hasNext  it.next() 
scala> val itb = Iterator(20,40,2,50,69, 90)
itb: Iterator[Int] = non-empty iterator
scala> itb.length
res41: Int = 0
scala> val a = Iterable(1, 2)
a: Iterable[Int] = List(1, 2)

scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> numbers. foldLeft(0)((m: Int, n: Int) => m + n)
res3: Int = 55
Tuple构建方法,(Tuple才有_1, _2, _3, _4操作, Map可以看作多个Tuple2)
scala> val t = new Tuple4("Scala", "hello", "aa", "bb")   
t: (java.lang.String, java.lang.String, java.lang.String, java.lang.String) = (Scala,hello,aa,bb)
scala> val t = (1, "hello", Console)
t: (Int, java.lang.String, Console.type) = (1,hello,scala.Console$@794564dc)

s.split(Array(' ', ',')).filter((_ != "")).map(_.split(":")) // 表示按两个符号来split, 空格或逗号

Map两种表示方法:

scala> val m = Map(("a", 1), ("b",2), ("c",3))
m: scala.collection.immutable.Map[java.lang.String,Int] = Map(a -> 1, b -> 2, c -> 3)

scala> val extensions:Map[String, Int] = Map("steve" -> 100, "bob" -> 101, "joe" -> 201)

extensions: Map[String,Int] = Map(steve -> 100, bob -> 101, joe -> 201)

scala> m.values
res32: Iterable[Int] = MapLike(1, 2, 3)

scala> m.values.toList(1)
res39: Int = 2

Map获取键和值的两种方法:

scala> extensions.filter((namePhone: (String, Int)) => namePhone._2 < 200)
res29: scala.collection.immutable.Map[String,Int] = Map(steve -> 100, bob -> 101)

scala> extensions.filter({case (name, extension) => extension < 200})
res30: scala.collection.immutable.Map[String,Int] = Map(steve -> 100, bob -> 101)

View produces a lazy collection, Elements are only evaluated once they are explicitly accessed
scala> (1 to 1000000000).filter(_%2==0).take(10).toList
java.lang.OutOfMemoryError: Java heap space
scala> (1 to 1000000000).view.filter(_%2==0).take(10).toList
res48: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
  • implicit-parameters

http://daily-scala.blogspot.hk/2010/04/implicit-parameters.html

  • scala vim 语法高亮插件、tags:

https://github.com/scala/scala-dist/tree/master/tool-support/src/vim

http://leonard.io/blog/2013/04/editing-scala-with-vim/

http://bleibinha.us/blog/2013/08/my-vim-setup-for-scala#ctags

  • sealed, transient ?
When a trait is " sealed" all of its subclasses are declared within the same file and that makes the set of subclasses finite which allows certain compiler checks.

Scala provides a  @transient annotation for fields that should not be serialized at all. If you mark a field as @transient, then the framework should not save the field even when the surrounding object is serialized. When the object is loaded, the field will be restored to the default value for the type of the field annotated as @transient.

  • scala-sbt

  groupID %% artifactID % revision rather than  groupID % artifactID % revision 

===================================================================
++ 连接两个数组

:: cons 将新元素加到列表开头
::: 实现叠加功能

scala> val t = List(2,3)
t: List[Int] = List(2, 3)

scala> val a = 1 :: t

a: List[Int] = List(1, 2, 3)

scala> val b = t :: 1
<console>:8: error: value :: is not a member of Int
val b = t :: 1
^

集成环境: 在eclipse的market里搜索、安装即可

上下限约束符:>:和<:

例子中A <: Closeable(java.io.Cloaseable)的意思就是保证类型参数A是Closeable的子类(含本类),语法“A <: B"定义了B为A的上界;同理相反的A>:B的意思就是A是B的超类(含本类),定义了B为A的下界. 其实<: 和 >: 就等价于java范型编程中的 extends,super

特质trait

java: Interface可以达到C++多继承的效果,也就是你说的多继承class。"实现"

public class Hero extends ActionCharacter implements CanFight,CanFly,CanSwim { ... }

Scala则通过特征(trait)来实现, 与接口不同的是,它还可以定义属性和方法的实现。Scala中特征被用于服务于单一目的功能模块的模块化中。通过混合这种特征(模块)群来实现各种应用程序的功能要求,Scala也是按照这个构想来设计的。“扩展”或“混入(mix in)”

class PianoplayingTeacher extends Person with TTeacher with TPianoPlayer { def ... }

==================================================================
lazy val words = ... //被声明为lazy时,它的初始化将被推迟,知道我们首次对它取值

for(i  <- 1 to 9 by 2)..     1 ... 9
for(i  <- 1 until 9 by 2)..  1 ... 8  (会产生一个Range对象)

:javap A

Iterable 默认只能有20+个

val xs  = List.range(1, 10) // [1 … 9]

xs.filter( x => 0 == x % 2).map(_ * 2).sum

map( (x: Int) => x * 2 )

place holder: _ 用于替换


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值