`
bd2007
  • 浏览: 385166 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

O'REILLY版《Programming Scala》学习笔记——基础语法部分

    博客分类:
  • java
阅读更多
    scala 学习笔记
//方法定义格式:def methodname(param1:string,param2:stirng):string={	...}

返回值类型以及前面的":"可以省略
如果方法体只是一个表达式可以去掉"{}"

scala必须明确指定类型的场景
1.定义变量的时候必须申明类型,除非这个变量在定义的同时并被赋值
2.所有方法参数必须申明类型
3.以下情况下方法的返回值需要明确定义类型
a.当在方法中明确使用return关键字返回
b.递归方法
c.当一个方法被重载并且当重载的方法调用其他同名方法时需要指定返回类型,如果是调用非同名方法则无需指定返回类型
d.当推断的返回值类型大于你的设想的时候,建议公开的api都指定返回值类型

当一个公共方法为定义范围值类型时,如果改变这个内部方法的实现,这个方法在编译后他的返回值类型可能被修改。
这个情况下如果有已经编译过的客户代码来调用这个方法可能会出错,这时需要重新编译客户端代码。
解决这个问题的最好办法是"公开的api都指定返回值类型"

当方法的返回值类型是自动推断的并且方法体前没有使用"=",scala将推断这个方法返回类型是unit
scala中方法体前有"="被认为是函数定义,如果没有被推断为是一个"procedure"返回类型是unit
val i=123 //整数类型赋值默认为intval l=123l; val ll=123l //如果要赋long值,需要在添加l或者l,这个和java的规则类似val b:byte=127 //变量定义声明类型后可以用合适大小的整数为其赋值3.14e-5d //double3.14e-5d //double3.14e-5  //double,默认3.14e-5f //float,要指定为单精度浮点型需要加上f或者f,这个和java的规则类似3.14e-5f //float

tuples 容纳的元素个数1-22
tuples类型变量实际上是scala.tuplen类的实例
//示例代码 startdef tupleator(x1: any, x2: any, x3: any) = (x1, x2, x3)val t = tupleator("hello", 1, 2.3)println( "print the whole tuple: " + t )println( "print the first item: " + t._1 ) //用t._n得到第n个元素,这里索引从1开始而不是0(索引从1开始是函数式编程的惯例)println( "print the second item: " + t._2 )println( "print the third item: " + t._3 )val (t1, t2, t3) = tupleator("world", '!', 0x22)println( t1 + " " + t2 + " " + t3 )//示例代码 end//输出结果:print the whole tuple: (hello,1,2.3)print the first item: helloprint the second item: 1print the third item: 2.3world ! 34

some,none是option的子类,none只是一个对象不是类。
scala中的空值使用none表示,类似java中的null
some.get 返回被some包装的值
none.get 会抛异常 throws a nosuchelementexception
statecapitals.get("unknown").getorelse("oops2!")  //getorelse 用法

scala的类名不用和文件名匹配,包名的定义也不依赖于目录的物理结构
scala脚本不允许定义包???
scala中import后的包路径是相对的,只有以"_root_"开始的包路径是绝对路径

scala基本概念:
1.scala允许非数字的方法名。+, -, $这些符号都可以作为方法名
2.1 + 2 等同于1 .+(2) 这里1后面必须紧跟一个空格,否则1.被看做是double。如果方法只有一个参数,可以不用"."和"()"
scala中方法名、类型名、变量名可以包含ascii字符,例如字母、数字、下划线(_)、$。单不能包括这些符号:(、)、[、]、{、},这些界定符号也不能包括:`、’、 '、"、.、;、,
scala一般的定义规则和java类似以一个字母或下划线开头后面可以跟随数字、字母、下划线或者$
$在scala中有内部含义,不能单独作为定义???

下划线(_)的作用:下划线的存在可以告诉编译器直到下一个空格位置的字符都是定义的一部分。例如val xyz_++= = 1 这里的“xyz_++=”是一个常量的名字,这个表达式的意思就是给常量“xyz_++=”初始化并赋值为1。表达式val xyz++= = 1将编译失败,编译器会看做xyz ++=“xyz”被当成一个变量。
如果下划线后面有操作符(+、-、=等)你不能在后面混合字母和数字,这样是为了防止表达式的含义混淆不清。例如:abc_=123 这个表达式的表示“abc_=123”是一个变量名呢?还是为变量“abc_”赋值为123?
如果标识符以操作符开头,那剩余部分也必须是操作符。
“``”可以用任何字符串来定义标识符。例如val `this is a valid identifier` = "hello
world!",这里`this is a valid identifier`是一个变量名。有些scala里的保留字也可以用“``”来转义,例如java.net.proxy.`type`()

一个无参数的方法定义的时候无需圆括号。
调用一个方法的时候如果不带参数,就不用使用圆括号。例如应该这样list(1, 2, 3).size使用,如果这样调用list(1,2,3).size()就会报错。
however, the length method for java.lang.string does have parentheses in its definition, but scala lets you write both "hello".length() and "hello".length.
当被调用的方法没有参数或者只有一个参数的时候可以忽略方法名前面的“.”
list(1, 2, 3) size和list(1, 2, 3).size等价

冒号结尾的方法是采用右绑定,其他方法都是左绑定。例如list的::方法
scala> val list = list('b', 'c', 'd')list: list[char] = list(b, c, d)scala> 'a' :: listres4: list[char] = list(a, b, c, d)

scala中if语句可以用来赋值,以下用法类似三元表达式:
val configfile = new java.io.file("~/.myapprc")val configfilepath = if (configfile.exists()) {configfile.getabsolutepath()} else {configfile.createnewfile()configfile.getabsolutepath()}

scala中for的用法:
1.foreach方式:
val dogbreeds = list("doberman", "yorkshire terrier", "dachshund","scottish terrier", "great dane", "portuguese water dog")for (breed <- dogbreeds)println(breed)

2.filtering 过滤
for (breed <- dogbreedsif breed.contains("terrier")) println(breed)

for (breed <- dogbreedsif breed.contains("terrier");//多个过滤语句用";"分隔if !breed.startswith("yorkshire")) println(breed)

3.yielding
//符合过滤条件的元素添加到filteredbreeds 这个list里val filteredbreeds = for {breed <- dogbreedsif breed.contains("terrier")//for语句使用"{}"包围的时候,多个过滤语句不用";"分隔if !breed.startswith("yorkshire")} yield breed

for {breed <- dogbreedsupcasedbreed = breed.touppercase()//upcasedbreed 在for语句里定义的变量(注意:没有使用val)} println(upcasedbreed)//upcasedbreed这里可以使用前面定义的变量


scala中没有“break”和“continue”;“&amp;&amp;”、“||”和java中一样是短路操作符号;“==”、“!=”不同于java在scala中是值比较。
val sundries = list(23, "hello", 8.5, 'q')for (sundry <- sundries) {sundry match {case i: int => println("got an integer: " + i)case s: string => println("got a string: " + s)case f: double => println("got a double: " + f)case other => println("got something else: " + other)//other 是匹配其他类型的通配符}}

val tupa = ("good", "morning!")val tupb = ("guten", "tag!")for (tup <- list(tupa, tupb)) {tup match {  case (thingone, thingtwo) if thingone == "good" =>    println("a two-tuple starting with 'good'.")//if做更细粒度的匹配  case (thingone, thingtwo) =>    println("this has two things: " + thingone + " and " + thingtwo)}}

关于模式匹配注意点:如果第一个case条件的匹配范围大于第二个case的范围,那么第二个case将永远不会被到达。这会导致一个编译器错误

//强大的模式匹配,可以直接匹配对象属性case class person(name: string, age: int)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("who are you, " + age + " year-old person named " + name + "?")}}


val bookextractorre = """book: title=([^,]+),\s+authors=(.+)""".r//调用string的r方法将字符串转成正则表达式val magazineextractorre = """magazine: title=([^,]+),\s+issue=(.+)""".rval catalog = list("book: title=programming scala, authors=dean wampler, alex payne","magazine: title=the new yorker, issue=january 2009","book: title=war and peace, authors=leo tolstoy","magazine: title=the atlantic, issue=february 2009","baddata: text=who put this here??")for (item <- catalog) {  item match {    case bookextractorre(title, authors) =>      println("book \"" + title + "\", written by " + authors)    case magazineextractorre(title, issue) =>      println("magazine \"" + title + "\", issue " + issue)    case entry => println("unrecognized entry: " + entry)  }}


scala中没有checked exceptions,方法定义的时候也没有throws子句。 
0
9
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics