Scala-2

scala的方法都可以是操作符 操作符也可以是方法

所以scala的代码可以这么美

object Test2  extends App{//App特质 可以省略main 但不能提供参数
    val scala ="scala"
   i love scala
}
object i{
  def love(s:String )=println("i"+" love .com"+s )
 }

输出结果
i love scala

import scala.collection.mutable.Map

object Test {//object与class重名  object Test是class Test的伴生对象 必须在同一个源文件内 class是object的伴生类
  val cache = Map[String, Int]()//伴生类和伴生对象可以互相访问其私有成员变量
  def calculate(s: String): Int = {
    if (cache.contains(s)) {
       cache(s)
    }
    else {
      val acc = new Test//在object用使用class Test
      val cs=acc.checkSum()
      for(c <- s){//把string 拆解为char
        acc.add(c.toByte)//.toByte把char转为ascii码 如果c是'a' 那么sum=0+97
        val cs =acc.checkSum()//cs初始值为0  现在cs是-97
        cache += (s -> cs)//增加一条映射 aaaa -> -97  映射的自加运算整数会相加
      }
         cs
    }
  }
}

class Test{
  private var sum=0
  def add(s:Byte)=sum+=s
  def checkSum():Int= ~(sum & 0xFF)+1 //返回sum 负数 sum转化为2进制作与运算 超过255会是正数
}
object Main {//main函数所在的class必须是 静态的
  def main(args: Array[String]): Unit = {

    println("hello world")
  }
}
/**
  * Created by root on 16-2-26.
  */
//自定义一个带有分式的有理数的类
class Rational(n: Int, d: Int) {
  require(d != 0)

  private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
  //递归求最大公约数 greatest common divisor
  private val g = gcd(n.abs, d.abs)

  val n1 = n/g
  //访问本类的成员 要加入字段 field
  val d1 = d/g

  override def toString = n1 + "/" + d1

  //加入字段便于使用 +默认会把Int转为String
  def add(that: Rational): Rational = new Rational(n1 * that.d1 + that.n1 * d1, d1 * that.d1)

  //有理分式的加法运算
  def lessThan(that: Rational): Boolean = (this.n1 * that.d1 < that.n1 * this.d1)

  // this指向当前类被构造对象的实例
  def max(that: Rational): Rational = if (this.lessThan(that)) that else this

  //求 this 和 that的最大值
  def this(n: Int) = this(n, 1) //简洁的辅助构造器  scala的所有的辅助构造器的第一个动作都是调用别的构造器
  //所以在scala中主构造器不可缺省 而且是唯一入口点

  def +(that:Rational):Rational=new Rational(n1 * that.d1 + that.n1 * d1, d1 * that.d1)
  //重载 + 方法 使分式有理数之间可以用+作运算

  def *(that:Rational):Rational=new Rational(this.n1*that.n1,this.d1 *that.d1)
  //重载 *方法  同理还可以重载 -方法 / 方法 或者 Rational和一些基本数据类型的运算还不仅仅是 Rational之间的运算


}

object Main extends App {
  val a = new Rational(2, 2)
  val d = new Rational(3, 3)
  println(a.add(d).toString)
  println(a lessThan d) //返回false
 println(a + d)
  println(a*d )
  //如果要记算 2 + Rational(1,1)
  //可以定义转换方法
  implicit def intToRational(x:Int)=new Rational(x)
  println(2+a)
}

循环的嵌套

import java.io.File

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

val filesHere=(new File(".")).listFiles
def grep(pattern: String)=
 for (
   file <- filesHere//外层循环
    if (file.getName.endsWith(".scala"));//当外层循环匹配到正确内容时执行内层循环
    line <- fileLines(file);//内层循环
   trimmed=line.trim //mid-stream 流间绑定
    if (trimmed.matches(pattern))) println(file + ":" + trimmed)//当内层循环体匹配到正确内容时执行print
//内层循环执行的部分不在for的括号当中


grep(".*gcd.*")//正则表达式
posted @ 2016-02-26 15:44  Salaku  阅读(240)  评论(0编辑  收藏  举报