阅读159 返回首页    go 技术社区[云栖]


Coursera Scala 2-5,6:类


Coursera Scala 2-5,6:类

class Rational(n: Int, d: Int) {
  require(d != 0)
  private val g = gcd(n.abs, d.abs)
  //将构造器传入的参数,赋值成成员变量,外部才可以访问
  val numer = n / g
  val denom = 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.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)
  //override关键字重载函数
  override def toString = numer+"/"+denom
  private def gcd(a: Int, b: Int): Int =
    if (b == 0) a else gcd(b, a % b)
}

富操作/中缀表达式

scala允许函数用如下表示:

富操作 原表示方法
r add s r.add(s)
r less s r.less(s)

优先级

scala中符号优先级,逐次增高
|
^
&
<>
= !

+ -
* / %

参考here


最后更新:2017-04-03 05:39:17

  上一篇:go Coursera Scala 4-3:子类型和泛型
  下一篇:go Coursera Scala 4-7:Lists