zoukankan      html  css  js  c++  java
  • Scala学习笔记——函数式对象

    用创建一个函数式对象(类Rational)的过程来说明

    类Rational是一种表示有理数(Rational number)的类

    package com.scala.first
    
    /**
      * Created by common on 17-4-3.
      */
    object Rational {
      def main(args: Array[String]) {
    
        var r1 = new Rational(1, 2)
        var r2 = new Rational(1)
        System.out.println(r1.toString)
        System.out.println(r1.add(r2).toString)
        var r3 = new Rational(2, 2)
        System.out.println(r3)
        System.out.println(r1 + r3)
      }
    }
    
    class Rational(n: Int, d: Int) {
      //检查先决条件,不符合先决条件将抛出IllegalArgumentException
      require(d != 0)
      //最大公约数
      private val g = gcd(n.abs, d.abs)
    
      private def gcd(a: Int, b: Int): Int = {
        if (b == 0) a else gcd(b, a % b)
      }
    
      //进行约分
      val numer: Int = n / g
      val denom: Int = d / g
    
      //辅助构造器
      def this(n: Int) = this(n, 1)
    
      //定义操作符
      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
        )
      }
    
      //方法重载
      override def toString = numer + "/" + denom
    
      //定义方法
      def add(that: Rational): Rational = {
        new Rational(
          numer * that.denom + that.numer * denom,
          denom * that.denom
        )
      }
    
      //定义方法,自指向this可写可不写
      def lessThan(that: Rational): Boolean = {
        this.numer * that.denom < that.numer * this.denom
      }
    
    
    }
    
  • 相关阅读:
    产品需求说明书PRD模版
    会编程的 AI + 会修 Bug 的 AI,等于什么 ?
    会编程的 AI + 会修 Bug 的 AI,等于什么 ?
    会编程的 AI + 会修 Bug 的 AI,等于什么 ?
    luogu P1164 小A点菜
    luogu P1347 排序
    luogu P1195 口袋的天空
    luogu P1182 数列分段Section II
    luogu P1332 血色先锋队
    luogu P1983 车站分级
  • 原文地址:https://www.cnblogs.com/tonglin0325/p/6664884.html
Copyright © 2011-2022 走看看