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

scala学习(二) 内建控制结构

 
阅读更多

for使用

常用

val filesHere = (new java.io.File(/".")).listFiles

for(file <- filesHere)

println(file)

 

过滤

val filesHere = (new java.io.File(/".")).listFiles

for(file <- filesHere  if file.getNmae.endWith(".scala") )  //有2个if的话 要用;分割

println(file)

 

嵌套枚举

def fileLInes(file:java.io.File) = scala.io.Source.fromFile(file).getLines.toList

def grep(pattern:String) =

for(

file <- fileHeres

        if file.getNmae.endWith(".scala")

        line <-fileLines(file)

if line.trim.matches(pattern

)println(file + ": " + line.trim)

grep(.*gcd.*)

 

 

 

制造新集合

def scalaFiles =

  for{

file <- fileHeres

if file.getNmae.endWith(".scala")

}yield file

 

异常处理

try{

val f = new FileReader("input.txt")

        //使用并关闭文件

}catch{

         case ex:FileNotFoundException => //处理丢失的文件

    case ex:IOException=> //处理其他的I/O错误

 

}finally{

 

f.close() //确保关闭文件

}

scala与java的区别是不需要捕获检查异常

 

 

}

 

匹配表达式

scala 的match类似java的switch

val firstArg = if (args.length>0) args(0) else ""

firstArg match{

case "salt" => println("pepper")

case "chips"=> println("salsa")

        case _ println("huh?")

 

}

_表示默认情况下

 

 

scala不在使用break和continue

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics