Scala学习笔记-函数式对象

package com.company

/**
 * Created by Larry on 2014/7/21.
 * Scala编程 第六章学习
 */
object Rational {
  /*n,d类参数,Scala编译器收集这2个类参数并创造出带同样的
  两个参数的主构造器*/
  class Rational(n: Int,d: Int) {
    /*先决条件*/
    require(d != 0)

    /*私有字段*/
    private val g = gcd(n.abs, d.abs)

    /*通过下面两句,Scala编译器才会产生包含2个Int类型
    字段(分别是numer和denom)的类*/
    val numer = n / g
    val denom = d / g

    /*辅助构造器*/
    def this(n: Int) = this(n,1)

    /*Scala编译器将把类内部的任何既不是字段也不是方法定义的代码
    * 编译至主构造器中*/
    override def toString = numer + "/" + denom //重写toString方法

    /*有理数相加 定义方法*/
    def add (that: Rational): Rational =
      new Rational(
        numer * that.denom + that.numer * denom,
        denom * that.denom
      )
    /*有理数相加 定义操作符*/
    def + (that: Rational): Rational =
      new Rational(
        numer * that.denom + that.numer * denom,
        denom * that.denom
      )
    /*有理数相加 方法重载*/
    def + (i: Int): Rational =
      new Rational(numer + i * denom, denom)
    /*有理数相建 定义操作符*/
    def - (that: Rational): Rational =
      new Rational(
        numer * that.denom - that.numer * denom,
        denom * that.denom
      )
    /*有理数相减 方法重载*/
    def - (i: Int): Rational =
      new Rational(numer - i * denom, denom)
    /*有理数想乘 定义操作符*/
    def * (that: Rational): Rational =
      new Rational(
        numer * that.numer,
        denom * that.denom
      )
    /*有理数相乘 方法重载*/
    def * (i: Int): Rational =
      new Rational(numer * i , denom)
    /*有理数相除 定义操作符*/
    def / (that: Rational): Rational =
      new Rational(
        numer * that.denom, denom * that.numer
      )
    /*有理数相除 方法重载*/
    def / (i: Int): Rational =
      new Rational(numer , denom * i)

    /*私有方法,求2个数最大公约数*/
    private def gcd(a: Int, b: Int): Int =
      if (b == 0) a else gcd(b, a % b)
  }

  def main (args: Array[String] ) {
    var x = new Rational(1,2)
    var y = new Rational(1,3)
    var z = new Rational(3)
    var m = new Rational(2)
    var n = new Rational(2,3)
    println((x - y) * x / n * z / m)

    /*隐式转换*/
    implicit def intToRational(x: Int) = new Rational(x)
    var k = new Rational(1,5)
    println(2 * k)

    /*println(x.add(new Rational(1,3)))
    println(x + new Rational(1,3))
    println(x .+(new Rational(1,3)) )
    println(x * new Rational(1,3))
    println(x.numer)
    println(x.denom)
    println(new Rational(8))
    println(new Rational(22,66))*/

  }
}

你可能感兴趣的:(编程,scala)