Scala 前置、中置、后置操作符

object OperatorDemo {

  def main(args: Array[String]): Unit = {
    val oper = new MyOper

    //普通调用方式
    oper.unary_~

    //前置调用,支持+、-、!、~
    ~oper //unary_~...

    //中置调用
    oper midOper 5 //midOper...

    //后置调用,可以看做无参的中置调用
    oper postOper //postOper...
    
  }

}

class MyOper {

  var num: Int = _

  def midOper(n: Int) = {
    println("midOper...")
  }

  def postOper(): Unit = {
    println("postOper...")
  }

  //前置操作符,方法名固定格式
  def unary_~() = {
    println("unary_~...")
  }
}

  

猜你喜欢

转载自www.cnblogs.com/noyouth/p/12766962.html