scala中的算术符重载代码详细解释
生活随笔
收集整理的這篇文章主要介紹了
scala中的算术符重载代码详细解释
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
overload_exercise.scala代碼如下:
object Overload_Exercise extends Serializable { //------------------------下面是被調(diào)用的子函數(shù)定義------------------------------------------------class Complex(val real: Int, val imaginary: Int) {def +(operand: Complex): Complex = {//這個(gè)函數(shù)返回的類型是類類型,該類類型是Complexnew Complex(real + operand.real, imaginary + operand.imaginary)}//這里的意思是,往這個(gè)COmplex的入口分別傳入兩個(gè)參數(shù),一個(gè)是實(shí)數(shù)部分,一個(gè)是虛數(shù)部分.override def toString(): String = //返回String類型,下面的中括號(hào)是返回的內(nèi)容.{real + (if (imaginary < 0) "" else "+") + imaginary + "i"} }//------------------------下面是主函數(shù)------------------------------------------------def main(args: Array[String]): Unit = {val c1 = new Complex(1, 2)//利用上面的class來(lái)建立一個(gè)對(duì)象val c2 = new Complex(2, -3)val sum = c1 + c2//注意,這里重載符號(hào)生效了,可以觀察到,被重載的+符號(hào)的函數(shù),被定義在該類中.println("(" + c1+ ")+ (" + c2 + ")=" + sum)}}運(yùn)行方法如下:
scalac overload_exercise.scala
scala Overload_Exercise
運(yùn)行結(jié)果是:
(1+2i)+ (2-3i)=3-1i
其實(shí),就是你想要+號(hào)的左右兩側(cè)分別處理某種class,
那么就在這個(gè)class內(nèi)部對(duì)符號(hào)進(jìn)行重載.
總結(jié)
以上是生活随笔為你收集整理的scala中的算术符重载代码详细解释的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: spark中的println失效问题解决
- 下一篇: 论文原文解读汇总(持续更新中)