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)
  }
}

转载于:https://www.cnblogs.com/Salaku/p/5222284.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值