閱讀159 返回首頁    go 阿裏雲 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