# 定義操作方法

``class Account(val id: String, val name: String) {    private var bal: Int = _    def deposit(amount: Int) {        require(amount > 0) // 不能存負數        bal += amount    }        def withdraw(amount: Int) {        require(amount > 0 && amount < bal) // 不能提負數，不能超過餘額        bal -= amount    }        def balance = bal}val acct = new Account("123-456-789", "Justin")acct deposit 100        // 等於 acct.deposit(100)acct withdraw 50        // 等於 acct.withdraw(50)println(acct.balance)   // 顯示 50``

``class Complex(val re: Double, val im: Double) {    def add (that: Complex) = new Complex(re + that.re, im + that.im)    def minus (that: Complex) = new Complex(re - that.re, im - that.im)    override def toString =      re + (if (im < 0) " - " + (-im) else " + " + im) + " i"}val c1 = new Complex(4, 2)val c2 = new Complex(2, 1)println(c1 add c2)       // 顯示 6.0 + 3.0 iprintln(c1 minus c2)     // 顯示 2.0 + 1.0 i``

``class Complex(val re: Double, val im: Double) {    def + (that: Complex) = new Complex(re + that.re, im + that.im)    def - (that: Complex) = new Complex(re - that.re, im - that.im)    def * (that: Complex) = new Complex(re * that.re - im * that.im,                                        re * that.im + im * that.re)    def / (that: Complex) = {      val d = that.re * that.re + that.im * that.im      new Complex((re * that.re + im * that.im) / d,                  (im * that.re - re * that.im) / d)    }    override def toString =      re + (if (im < 0) " - " + (-im) else " + " + im) + " i"}val c1 = new Complex(4, 2)val c2 = new Complex(2, 1)println(c1 + c2)    // 顯示 6.0 + 3.0 iprintln(c1 - c2)    // 顯示 2.0 + 1.0 iprintln(c1 * c2)    // 顯示 6.0 + 8.0 iprintln(c1 / c2)    // 顯示 2.0 + 0.0 i``

• 算術操作：如+、-、*、/、%
• 關係操作：如>、>=、<、<=
• 邏輯操作：如&&、||、!
• 位元操作：如&、|、~、^、>>、>>>、<<
• 指定操作：如+=、-=、*=、/=、%=、&=、|=、~=、>>=、>>>=、<<=

scala> ~2
res15: Int = -3

scala> (2).unary_~
res16: Int = -3

scala>