Scala-3

Scala的for表达式可以有返回值

object Main extends App {
  val x=Array(1,2,3,4,5,6)  //等待枚举的字符串
  def splitX(x:Array[Int])=for{
    i <- x              //拆解
    if (i>2)   //过滤条件
  }yield i 

  val y=splitX(x)
  println(y)

}

结果val y=Array(3,4,5,6)

for{子句} yield{循环体} yield要在整个循环体之前 例如 yield i

object test1 extends App{
 print(tools.multiTable())

}
object tools {
  def makeRowSeq(row:Int)= {
    for (col <- 1 to 10) yield {
    val prod = (row * col).toString
      val padding=" "*(4-prod.length)
      padding+prod
  }

  }
  def makeRow(row:Int):String=makeRowSeq(row).mkString
  def multiTable()={
    val tableSeq=for (row <- 1 to 10)yield{
            makeRow(row)
    }
    tableSeq.mkString("\n")
  }
}

函数风格的文件读取

import scala.io.Source
object LongLines {
  def processFile(filename:String,width:Int)={
    val source =Source.fromFile(filename) //获得文件对象
     for (line <- source.getLines) //一行一行枚举
       processLine(filename,width,line)
  }
  private def processLine(filename:String,width:Int,line:String)={//processLine 方法
    if (line.length>width)println(filename+":"+line.trim)//三个参数 文件名 宽度 行
  }  //输出指定文件 的 特定行 当行// 的宽度大于给定的值
}
LongLines.processFile("test.scala",2)

scala脚本

import scala.io.Source

object tools{
  private def processFile1(fileName:String,width:Int,line:String): Unit ={
    if(line.length>width)println(fileName+" : "+line.trim)
  }
  def processFile(fileName:String,width:Int): Unit ={
    val file= Source.fromFile(fileName)
    for(line <- file.getLines)processFile1(fileName,width,line)
  }
  def main(args: Array[String]): Unit = {
    val width = args(0).toInt
    for (arg <- args.drop(1)) processFile(arg, width)
  }
}
posted @ 2016-02-27 13:56  Salaku  阅读(250)  评论(0编辑  收藏  举报