Scala入门笔记

[toc]

0 hello world

object Hello {  
  def main(args: Array[String]) = println("Hello world")  
}

or

object Hello extends App {
  println("Hello World")
}

1变量

  • val 定义 immutable variable
  • var 定义 mutable vraiable
  • lazy val 赋值是不会计算值,调用才计算
    可以不显示指定变量的类型,scala会自动进行类型推导

2 类型


scala类型系统以Any为根,分为AnyRef和AnyVal 两个分支体系,在AnyRef分支的最底层,有个Null类型的特殊类型,它被当作是所有AnyRef类型的子类型。更进一步在两个分支共同的最底层类型是Nothing类型,它被当作所有AnyRef和AnyVal类型的子类型。

2.1 umerical类型

  • Byte 1字节
  • Short 2
  • Int 4
  • Long 8
  • Foat
  • Double
    高精度类型 a = 低精度类型 b (同c自动转换)
    低精度类型 b = 高精度类型 a (error :type mismatch)

2.2 Boolen 类型

false
true

2.3 Char 类型

16 bit unsigned Unicode character. Range from U+0000 to U+FFFF

2.4 Unit 类型

it is not represented by any object in the underlying runtime system
A method with return type Unit is analogous to a Java method which is declared void.

val p=()

2.5 Null

Null类型只有一个唯一的值:null,可以被赋给所有的AnyRef类型变量
List(Null,Null,1)

2.6 Nothing

程序异常返回

2.7 String

val name =jin
s"my name is ${name}"

3 Block代码块

Block 也是一个表达式,其最终的求得的值是最后一个表达式的值

# 单行
{exp1;exp2}

{
exp1
exp2
}

4 函数

4.0 一等公民

  • 函数作为实参传递给另一函数
  • 函数作为返回值
  • 把函数赋值为变量
  • 把函数储存在数据结构里

4.0 .1函数类型

函数的类型格式为:A => B,表示一个接受A的参数,并返回B的参数

Int => String 是把整型函数映射为字符串的函数类型

4.0.2 高阶函数

用函数作为形参或者返回值的函数

// 参数是一个函数,这个函数有两个Int的参数,返回一个Int参数.
def operate(f:(Int, Int) =>Int) ={
    f(4,4)
def add() = (x:Int, y:Int) => { x+ y}
}

4.1 定义

def functionName (param: Param Type):Reurn Type = {
//function body:expression 
}
# 单行
def functionName (param: Param Type):Reurn Type = function body:expression 
def hello(para:String):String={   "hello"+ para}

4.2 调用方式的不同

  • call by value 调用时计算参数的值
    def test(x:Int, y:Int) = x+y
  • call by name 调用时不计算参数的值
    def test(x:=>Int y:=>Int Y) = x+y
def bar(x:Int,y:=>Int) = 1
def loop():Int = loop
bar(1,loop()) # 1
bar(loop(),1)  # 死循环

疑问?

def loop():Int = loop
loop

为什么会死循环呢?
https://stackoverflow.com/questions/43561397/scala-def-loop-unit-loop-why-loop-forever

4.3 匿名函数

匿名函数的定义:
(形参列表) => { 函数体 }

(x:Int, y:Int) => { x+ y}
val add = (x:Int, y:Int) => { x+ y}

4.4 柯里化,偏函数

柯里化函数(Curried Function) 把具有多个参数的函数转化为一条函数链,每一个节点上是单一函数

def add(x:Int, y:Int) = x+y
def add(x:Int)(y:Inr) = x+y
def curriedAdd(a:Int)(b:Int) = a+b
curriedAdd(2)(2)
val addOne = curriedAdd(1)_
def curriedAdd1(a:Int, b:Int) = a+b
def curriedAdd(a:Int,b:Int) = a+b
def addTwo = curriedAdd( _:Int , 1:Int)

4.5 可变长度参数

参数:类型* 类似于Python的参数收集args,*kwargs

def capitalizeAll(args: String*) = {
  args.map { arg =>
    arg.capitalize
  }
}

5 控制语句

5.1 if 表达式

if(logical) vala else valb
if( x == 10 ){
         println("Value of X is 10");      } 
else if( x == 20 ){ 
         println("Value of X is 20");      }
 else if( x == 30 ){ 
         println("Value of X is 30");      }
 else{         println("This is else statement");      }

5.2 for

for( a <- 1 to 10){ 
         println( "Value of a: " + a );
// for loop execution with a range
for( a <- 1 until 10){ 
       println( "Value of a: " + a );      }
  • 多个参数
            // for loop execution with a range
for( a <- 1 to 3; b <- 1 to 3){
         println( "Value of a: " + a );
         println( "Value of b: " + b );
      }
  • 过滤
val numList = List(1,2,3,4,5,6,7,8,9,10);
// for loop execution with multiple filters
for( a <- numList   if a != 3; if a < 8 ){
         println( "Value of a: " + a );
      }
  • 列表推导
var a = 0;
val numList = List(1,2,3,4,5,6,7,8,9,10);
var retVal = for{ a <- numList 
                            if a != 3; 
                            if a < 8;
                            s = a +1 }
                            yield s

5.3 while 和 do while

var a = 10;
     // while loop execution
      while( a < 20 ){
         println( "Value of a: " + a ); 
         a = a + 1;}
 // do loop execution
do {        
        println( "Value of a: " + a );
         a = a + 1;
      }
      while( a < 20 )   }

5.4 match表达式

val alice = new Person("Alice", 25)
val bob = new Person("Bob", 32)
val charlie = new Person("Charlie", 32)
for (person <- List(alice, bob, charlie)) {
 
         person match { 
            case Person("Alice", 25) => println("Hi Alice!")
            case Person("Bob", 32) => println("Hi Bob!") 
            case Person(name, age) => println(
               "Age: " + age + " year, name: " + name + "?")
         }
      } 
   }
#这个类是特殊的用以比较的类
case class Person(name: String, age: Int)
>>>
Hi Alice!
Hi Bob! 
Age: 32 year, name: Charlie?

6 异常

try {         
        val f = new FileReader("input.txt")
      } catch {
         case ex: FileNotFoundException => {
            println("Missing file exception")}
         case ex: IOException => {   
         println("IO Exception") } 
      } finally { 
         println("Exiting finally...")
        throw new RuntimeException("n must be even")
      }

7 类

7.1 class

7.1.1 定义

  • 构造函数
    构造函数不是特殊的方法,他们是除了类的方法定义之外的代码。
class MyClass(x: Int, y: Int) {           // Defines a new type MyClass with a constructor  
  require(y > 0, "y must be positive")    // precondition, triggering an IllegalArgumentException if not met  
  def this (x: Int) = { ... }             // auxiliary constructor   
  def nb1 = x                             // public method computed every time it is called  
  def nb2 = y  
  private def test(a: Int): Int = { ... } // private method  
  val nb3 = x + y                         // computed only once  
  override def toString =                 // overridden method  
      member1 + ", " + member2 
  }

new MyClass(1, 2) // creates a new object of type

7.1.2 承继

abstract class TopLevel {     // abstract class  
  def method1(x: Int): Int   // abstract method  
  def method2(x: Int): Int = { ... }  
}

class Level1 extends TopLevel {  
  def method1(x: Int): Int = { ... }  
  override def method2(x: Int): Int = { ...} // TopLevel's method2 needs to be explicitly overridden  
}

object MyObject extends TopLevel { ... } // defines a singleton object. No other instance can be created

7.1.3 Case Classes

Case Class 是一种特殊的class类型,默认的case class 是不可变类型 .可以通过值比较.
基本的定义如下

case class Point(x: Int, y: Int)

可以不通过new 关键字实例化

val point = Point(1, 2)
val anotherPoint = Point(1, 2)
val yetAnotherPoint = Point(2, 2)

比较


if (point == anotherPoint) {
  println(point + " and " + anotherPoint + " are the same.")
} else {
  println(point + " and " + anotherPoint + " are different.")
}
// Point(1,2) and Point(1,2) are the same.
if (point == yetAnotherPoint) {
  println(point + " and " + yetAnotherPoint + " are the same.")
} else {
  println(point + " and " + yetAnotherPoint + " are different.")
}
// Point(1,2) and Point(2,2) are different.

7.2 object 单例

作为一个定义的类的单例

object IdFactory {
  private var counter = 0
  def create(): Int = {
    counter += 1
    counter
  }
}
val newId: Int = IdFactory.create()
println(newId) // 1

7.3 Traits特质

类似于java8的借口
是一些字段和行为的集合,可以扩展或混入(mixin)你的类中。

trait Car {
  val brand: String
}

trait Shiny {
  val shineRefraction: Int
}
class BMW extends Car {
  val brand = "BMW"
}

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

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

8 collection 内置数据结构

Immutable Collections 不可变对象

  • List (linked list, provides fast sequential access)
  • Stream (same as List, except that the tail is evaluated only on demand)
  • Vector (array-like type, implemented as tree of blocks, provides fast random access)
  • Range (ordered sequence of integers with equal spacing)
  • String (Java type, implicitly converted to a character sequence, so you can treat every string like a Seq[Char])
  • Map (collection that maps keys to values)
  • Set (collection without duplicate elements)

Mutable Collections 可变对象

  • Array (Scala arrays are native JVM arrays at runtime, therefore they are very performant)
  • Scala also has mutable maps and sets; these should only be used if there are performance issues with immutable types
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,264评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,549评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,389评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,616评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,461评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,351评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,776评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,414评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,722评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,760评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,537评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,381评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,787评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,030评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,304评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,734评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,943评论 2 336

推荐阅读更多精彩内容

  • 22.13.main方法 Scala的main方法(类似java的static方法)必须定义在一个object内:...
    时待吾阅读 737评论 0 0
  • 变量初始化可以用用 _ 作占位符,赋值为默认值,字符串 null,Float、Int、Double 等为 0var...
    FaDeo_O阅读 894评论 0 0
  • 本博客采用创作共用版权协议, 要求署名、非商业用途和保持一致. 转载本博客文章必须也遵循署名-非商业用途-保持一致...
    Andrew_liu阅读 3,735评论 0 29
  • scala学习笔记 第2章 变量和数据类型 基本数据 scala的核心数据为四种 :字面量、值、变量、类型 值使...
    485b1aca799e阅读 2,103评论 0 1
  • 配置前提: 1台开发电脑,我本地是windows10,(主要用来提交开发的网站代码) 1台git服务器,已安装好g...
    xiaomalover阅读 881评论 0 0