【Kotlin】筆記

一:Boat

1. 菜鳥教程

2. 視圖綁定:kotlin直接可以訪問layout,在導包處加一個聲明即可(用的時候自動選擇)

](https://img-blog.csdnimg.cn/20200420090112327.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM4MzA0Njcy,size_16,color_FFFFFF,t_70)

二:基礎語法

1. range區間,for循環方式

for (x in 1..5) {
    print(x)
}

2. Array取代數組

1)val a = arrayOf(1, 2, 3)
2)val b = Array(3, { i -> (i * 2) }) 三個值,每個值爲i*2

3. inline內聯聲明當一種函數內部不需要在傳遞參數給其他函數時,使用該關鍵字編譯器可以直接將函數與我們的調用替換。

4. 主次構造函數

1)主構造函數不能包含任何的代碼。
a.主構造函數的參數自動成爲類的成員屬性。
b.初始化的代碼可以放到以 init 關鍵字作爲前綴的初始化塊(initializer blocks),其中init{}代碼塊體現了執行的順序。
c.Kotlin沒有static關鍵字,因此不存在靜態成員,伴生對象成員可以起到靜態成員的作用
2)次構造函數都要,或直接或間接通過另一個次構造函數代理主構造函數。比如使用this關鍵字。
3)執行順序首先會按順序執行類中init代碼塊,然後再執行構造方法裏代碼,並且我可以在init代碼塊中使用類聲明的屬性

5. 惰性加載,一種延遲加載的功能.

1)lateinit一般用於var
2)by lazy一般用於val

6. 伴生對象與匿名內部類

1)Kotlin中並沒有延用static這個關鍵字,而是使用伴生對象實現,在class內部聲明一個companion object代碼塊,其內部的成員變量和方法都將被編譯成爲靜態的。
2)針對那些獲取抽象類或者接口對象而來的。最常見的匿名內部類點擊事件。會用到
object。
3)區別:companion object代碼塊中的成員變量最終會被聲明到外部類中,也這是爲什麼我們能通過外部類名直接訪問,而object類則需要用外部類.內部類的方式調。
4)匿名內部類

7. 嵌套類與內部類

a)一個類內部聲明在另一個類內部,默認情況下,稱爲嵌套類。Kotlin的嵌套類和Java的靜態內部類相似,不能訪問外層類的實例成員。
b)內部類持有外層類對象的引用,可以訪問外層類的實例成員,使用inner標記:
c)匿名內部類:採用對象表達式來創建接口對象,即匿名內部類的實例。
c1)來自知乎,匿名內部類
c2)首先有一個接口,接口內含一個待實現方法
c3)創建一個方法,參數是哪個接口對象,利用這個對象實現接口方法

window.addMouseListener(object : MouseAdapter() {

    override fun mouseClicked(e: MouseEvent) { …… }

    override fun mouseEntered(e: MouseEvent) { …… }
})

8. 接口

1)若接口的方法只有一個,可以直接省去實現接口參數,直接複寫方法就好了

9. 拓展函數

10. reified內聯函數可以提高程序的性能,對於泛型函數,內聯具化可以使內聯泛型函數運行時保持它的具體類型參數

11. 函數類型通項式:(A, B) -> C

1) (x: Int, y: Int) -> Point
2)通過A.方法指定接收者對象 A.(B) -> C

12. Lambda表達式

1)val sum: (Int, Int) -> Int = { x: Int, y: Int -> x + y }
2)利用自動推斷模式:val sum = { x, y -> x + y }
3)其中只有一個參數,編譯器可以自動識別簽名,就可以不用聲明唯一的參數並且省略 -> , 該參數會隱式聲明爲 it :

13. 單例模式提供一種唯一對象的訪問模式

14. 作用域

  1. ?.let?:
    1)val l = b?.length ?: -1 這個和c裏面的三目運算符很像
    2)let 經常用於僅使用非空值執行代碼塊。如需對非空對象執行操作,可對其使用安全調用操作符 ?.
  2. it,經常作爲一參函數的指代參數
  3. 對於不會改變上下文對象的操作,可使用 also,例如記錄或打印調試信息。
val numbers = mutableListOf("one", "two", "three")

numbers

    .also { println("The list elements before adding new one: $it") }

    .add("four")
  1. 對於不返回值且主要在接收者(this)對象的成員上運行的代碼塊使用 apply,即將以下賦值操作應用於對象
val adam = Person("Adam").apply {

    age = 32

    city = "London"       

}

println(adam)
  1. with上下文對象作爲參數傳遞
  2. run 和 with 做同樣的事情,但是調用方式和 let 一樣——作爲上下文對象的擴展函數。當 lambda 表達式同時包含對象初始化和返回值的計算時,run 很有用

15.註解

  1. 定義:把元數據(Metadata)附加到代碼上,然後可以在編譯期或運行期訪問這些元數據
  2. 舉例 :比方是要調一個參數或方法,程序通過上下文沒法指定,就用這個來(普通註解)
@Fancy class Foo {
    @Fancy fun baz(@Fancy foo: Int): Int {
        return (@Fancy 1)
    }
}
  1. 元註解
Kotlin標準庫中定義了以下元註解:

@Target 指定可以用該註解標註的元素的可能的類型(類、函數、屬性、表達式等);
@Retention 指定該註解是否存儲在編譯後的 class 文件中,以及它在運行時能否通過反射可見 (默認都是 true);
@Repeatable 允許在單個元素上多次使用相同的該註解;
@MustBeDocumented 指定該註解是公有 API 的一部分,並且應該包含在生成的 API 文檔中顯示的類或方法的簽名中。
 

@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION,AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
annotation class Fancy
大部分相關的類位於包kotlin.annotation中

三:遇見問題

  1. 【安卓】import android.R
    1)舉例R.id.myTextView1是指向佈局中的空間TextView,layout文件夾下找就能看到它
    2)使用import android.R後 如果使用的話R.id就會去R包下面去找,報錯

四:java式代碼轉Kotlin例子

例一:

  1. 這個例子java口味非常重【LocalMusicAdapter】kotlin的主構造方法傳入兩個參數,var一下之後 內部就可以直接用【就相當於構造方法初始化過了】
    1)註釋掉的那個構造方法,十分明確的java構造寫法,kotlin特性直接在主構造方法傳入兩個參數,var一下之後 內部就可以直接用
    2)ViewHolder初始化,接着使用init方法自動初始化就好了
package com.ywjh.localfaraway

class LocalMusicAdapter(): RecyclerView.Adapter<LocalMusicAdapter.LocalMusicViewHolder>() {

    //傳入數據源
    var context: Context?=null
    var mDatas: MutableList<LocalMusicBean>? = null
    //創建構造方法



    constructor(context: Context?, mDatas: MutableList<LocalMusicBean>?) : this() {
        this.context = context
        this.mDatas = mDatas
    }



//    fun LocalMusicAdapter(context: Context, mDatas: List<LocalMusicBean>) {
//        this.context = context
//        this.mDatas = mDatas
//    }

    //創建並返回 ViewHolder 生成與初始化
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocalMusicViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.item_local_music, parent, false)
        val holder = LocalMusicViewHolder(view)
        return holder
    }
    //返回條目數量
    override fun getItemCount(): Int {
        return mDatas!!.size
    }
    //綁定Viewholder 拿到holser後對TextView進行設置
    override fun onBindViewHolder(holder: LocalMusicViewHolder, position: Int) {
        val musicBean = mDatas?.get(position)
        holder.idTv?.setText(musicBean!!.getId())
        holder.songTv?.setText(musicBean!!.getSong())
        holder.singerTv?.setText(musicBean!!.getSinger())
        holder.albumTv?.setText(musicBean!!.getAlbum())
        holder.timeTv?.setText(musicBean!!.getDuration())

        //holder.itemView.setOnClickListener { v -> onItemClickListener.OnItemClick(v, position) }
    }


    class LocalMusicViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        //繼承recycleView和ViewHolder內部類
        var idTv: TextView? = null
        var songTv:TextView? = null
        var singerTv:TextView? = null
        var albumTv:TextView? = null
        var timeTv:TextView? = null

        public fun LocalMusicViewHolder(itemView: View) {//kotlin 當中沒有這種構造方法,所有不會進行初始化

            idTv = itemView.findViewById(R.id.item_local_music_num)
            songTv = itemView.findViewById(R.id.item_local_music_song)
            singerTv = itemView.findViewById(R.id.item_local_music_singer)
            albumTv = itemView.findViewById(R.id.item_local_music_album)
            timeTv = itemView.findViewById(R.id.item_local_music_durtion)

        }



    }
}


轉kotlin

package com.ywjh.localfaraway


class LocalMusicAdapter(internal var context: Context, internal var mDatas: List<LocalMusicBean>) ://傳入上下文和List
    RecyclerView.Adapter<LocalMusicAdapter.LocalMusicViewHolder>() {//kotlin設置數據源可以直接放裏面




    //J1:寫一個接口   含有一個方法獲取  用於(獲取)傳入View以及位置
    interface OnItemClickListenerM {
        fun OnItemClick(view: View, position: Int)//點擊位置的position傳進去
    }
    //j2通過函數傳遞接口   創建接口對象實現
    internal lateinit var onItemClickListenerm: OnItemClickListenerM
    //j3 對象
    fun setOnItemClickListenerM(onItemClickListenerm: OnItemClickListenerM) {//該接口對象初始化
        this.onItemClickListenerm = onItemClickListenerm
    }


//v1先定義Viewholde內部類             這裏定義的itemView是可以直接用的
    inner class LocalMusicViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {//直接構造方法拿到View
        //var idTv: TextView 核心是拿到View

        var albumIg:ImageView?=null
        var songTv: TextView
        var singerTv: TextView
        var albumTv: TextView
        var timeTv: TextView




    //v2.用於顯示到View界面上
        init {
            //idTv = itemView.findViewById(R.id.item_local_music_num)
            albumIg= itemView.findViewById(R.id.item_local_music_albumpic)
            songTv = itemView.findViewById(R.id.item_local_music_song)
            songTv = itemView.findViewById(R.id.item_local_music_song)
            singerTv = itemView.findViewById(R.id.item_local_music_singer)
            albumTv = itemView.findViewById(R.id.item_local_music_album)
            timeTv = itemView.findViewById(R.id.item_local_music_durtion)
        }
    }


    //1獲取context上下文 創建holder對象 通過View創建holder
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocalMusicViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.item_local_music, parent, false)
        val holder = LocalMusicViewHolder(view)//內部類holder
         return holder//拿到holder也行
    }
//綁定界面1.創建ViewHolder方法進行賦值  2.kotlin惰性加載
//2.點擊事件:java 監聽外層view 找每條holder的記錄
    //kotlin 定義

    //recycleView和listview不一樣 未封裝成型的點擊事件類
    //在onbind中可以獲取每項的itemview 設定一個接口 自己封裝,調用onitemlistener



//2爲子項賦值 每次回滾時執行實時富裕項目
    override fun onBindViewHolder(holder: LocalMusicViewHolder, position: Int) {
        var musicBean:LocalMusicBean ?=null
        musicBean = mDatas[position]
        // holder.idTv.setText(musicBean.getId())
        holder.songTv.setText(musicBean.getSong())
        holder.singerTv.setText(musicBean.getSinger())
        holder.albumTv.setText(musicBean.getAlbum())
        holder.timeTv.setText(musicBean.getDuration())

       if (musicBean.getthumb()!=null)
       holder.albumIg?.setImageBitmap(musicBean.getthumb())

        holder.itemView.setOnClickListener { //每項被點擊時實現接口回調 回調的數據是v和position
            //監聽父view  設置點擊該view的 onItemClickListenerm賦予view和position
                v -> onItemClickListenerm?.OnItemClick(v, position)
        }
    }


//3計數
    override fun getItemCount(): Int {
        return mDatas.size
    }


}

例二

1.

import java.util.TreeMap

fun main(args: Array<String>) {
    var a="zero"
    val b:Long=1231
    //類型轉換
    var l=12
    var m="12"
    l=m.toInt()
    m=l.toString()
    println(a)
    println(b)
    sayHello()
    println(diary("panada"))
    println(getmess(null))
    var nums=1..10//聲明數組區間
    for(num in nums)
        print(num)
    //list 的引用
    var lists= listOf("1","2",3)
//    for(list in lists)
//        print(list)
//有序列
    for((i,e)in lists.withIndex()) {
        println("$i $e")
    }

    //map運用 類似詞典 且有索引
    var map=TreeMap<String,String>()
    map["好"]="good"
    map["學"]="study"
    map["向上"]="up"
     println(map["好"])
    print(z(3,5))
    //ps調用float單精度area(3.0f,3.0f)
}
//函數
fun sayHello(){
    println("Hello")
}
//無參數無返回類型
//fun sum(a: Int, b: Int): Int=x+y
fun sum(a: Int, b: Int): Int {   // Int 參數,返回值 Int
    return a + b
}

var z={x:Int,y:Int -> x+y}
var y:(Int,Int)->Int={x,y ->x+y}
//print包裹dollar參數取值
fun diary(place:String):String{
    var message="你好${place}"
    return message
}
//排除空指針異常+?表示傳入可爲“null”
fun getmess(mess:String?):String{
    return "得到"+mess
}
//switch與when語句
fun grade(score:Int){
    when(score){
        10-> print("考了滿分")
        8-> print("考的不錯")
        else-> print("繼續加油")
    }
}

2.輸入輸出

fun main(args: Array<String>){
    while (true){


    println("請輸入第一個數字")
    var num1= readLine()
    println("請輸入第二個數字")
    var num2= readLine()
//35字符串連接
/*    var num3=num1?.toInt()
    var num4=num1?.toInt()
    println("${num3}+${num4}=${num3+num4}")*/
//?輸入爲空則空,但空和空無法相加會報錯 !!拋出空指針異常
    //更新輸入a拋出異常,結合while就可以一直運行,不報運行代碼錯誤
    try {
    var num3:Int=num1!!.toInt()
    var num4:Int=num2!!.toInt()
    println("${num3}+${num4}=${num3+num4}")
    }catch (e:Exception){
        println("大哥,你輸入的有問題吧 ")
    }
}
}

3.方法調用

class Girl(var chactor:String,var voice:String){//靜態構造
    //兩個動態方法
    fun smile(){
        println("妹子笑了一下,麼麼噠")
    }

    fun cry(){
        println("嗚嗚嗚,人家傷心")
    }
}

fun main(args: Array<String>){
    var girl1=Girl(chactor = "溫柔",voice = "甜美")
    print("girl1這位妹子的聲音:${girl1.voice}")
    girl1.cry()
    girl1.smile()

}

例三:讀寫流BufferedReader和BufferedWritersubstring() 方法 區間取值

import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException

//導入java.io包下的BufferedReader類
//導入java.io包下的FileReader類
//導入java.io包下的IOException類
object SameAndDifferent {
    //類名
    @JvmStatic
    fun main(args: Array<String>) { //程序主入口函數,帶命令行參數
        val Al1= ArrayList<String>()
     
        try { //try代碼塊,當發生異常時會轉到catch代碼塊中
//讀取指定的文件

            val inFile =
                BufferedReader(FileReader("E:\\sametest\\sequence.txt"))
            var str1: String? //定義一個字符串類型變量str
            //var string1= arrayOfNulls<String>(1000)
            var i = 0 //定義一個整型變量
            while (inFile.readLine().also { str1 = it } != null) { //readLine()方法, 用於讀取一行,只要讀取內容不爲空就一直執行
                if(str1!!.indexOf("<h4>")!=-1&&str1!!.indexOf("</h4>")!=-1){
                   str1 = str1!!.substring(str1!!.indexOf(".html")+7, str1!!.indexOf("</a>"))
                    //第2799行:<h4><a href="../to-sorted-set.html">toSortedSet 測試
                    //str1 = str1!!.substring(str1!!.indexOf(".html'>")+1, str1!!.length)
                    //第2763行:<h4><a href="../to-mutable-list.html">toMutableList</a></h4>

                   // var str2=str1!!.substring(str1!!.indexOf(".html'>")+1, str1!!.indexOf("</a>"))
                    val bytes = str1!!.toByteArray() //獲得字節數
                    val getname:String=str1!!.trim()
                    Al1.add(getname)
                    for (j in Al1) {
                        println(j)
                    }
                   //println(getname) //輸出從每一行讀取的內容
                   //println("第" + i + "行有" + bytes.size + "個字節" + str1!!.length + "個字符") //輸出每一行的字符和字節個數
                }
                i++

            }
        } catch (e: IOException) { //當try代碼塊有異常時轉到catch代碼塊
            e.printStackTrace() //printStackTrace()方法是打印異常信息在程序中出錯的位置及原因
        }

例四:set集合的運用


import java.util.Collections.addAll
import java.util.ArrayList
import java.util.HashSet


fun main(args: Array<String>) {
    val result = HashSet<Int>()
    val set1 = object : HashSet<Int>() {
        init {//伴生初始化方法
            add(1)
            add(3)
            add(5)
        }
    }

    val set2 = object : HashSet<Int>() {
        init {
            add(1)
            add(2)
            add(3)
        }
    }

    result.clear()//result一個結果集 首先清除0 
    result.addAll(set1)//將set1結果集存入
    println("去重複交集前1:$set1")
    println("去重複交集前2:$set2")
    result.retainAll(set2)//retatinAll(保留所有相同的結果集)
    println("set1與set2的交集是:$result")

    result.clear()
    result.addAll(set2)
    println("差集前的1:$set1")
    println("差集前的2:$set2")
    result.removeAll(set1)//移除即可
    println("set2與set1的差集是:$result")

    result.clear()
    result.addAll(set1)
    result.addAll(set2)

    print("set1和set2的並集:$result")
    System.err.print("set1集合並集:是去重複" + "\n")


    val list = ArrayList<Int>()
    val list1 = object : ArrayList<Int>() {
        init {
            add(1)
            add(3)
            add(5)
        }
    }

    val list2 = object : ArrayList<Int>() {
        init {
            add(1)
            add(2)
            add(3)
        }
    }

    list.clear()
    list.addAll(list1)
    println("去重複交集前1:$list1")
    println("去重複交集前2:$list2")
    list.retainAll(list2)
    println("list1與list2的交集是:$list")

    list.clear()
    list.addAll(list2)
    println("差集前的1:$list1")
    println("差集前的2:$list2")
    list.removeAll(list1)
    println("list2與list1的差集是:$list")

    list.clear()
    list.addAll(list1)
    list.addAll(list2)

    print("list1和set2的並集:$list")
    System.err.print("List集合並集:是不會去重複")

}

例五:數據類的運用

1:老師講的

data class Complex(val re: Double=0.0, val im: Double=0.0) {  //主構造器初始化
   constructor( re:Int, im:Int):this(re.toDouble(),im.toDouble())
//傳入其他類型的參數     通過this轉換後委託主構造器 
   constructor( re:Double, im:Int):this(re,im.toDouble())
   constructor( re:Int, im:Double):this(re.toDouble(),im)
   
  //加減乘除方法簡化   operator操作符的重載
   operator fun plus(other:Complex) = Complex(re+other.re,im+other.im)
   operator fun minus(other:Complex) = Complex(re-other.re,im-other.im)
   operator fun times(other:Complex) = Complex(re*other.re - im*other.im,re*other.im + other.re*im)
   operator fun div(other:Complex) = with( other.re*other.re + other.im*other.im ) {
                                                Complex( (re*other.re + im*other.im)/this,(other.re*im - re*other.im)/this)
                                           }

   fun modulus() = Math.sqrt(re*re + im*im)


   
   override fun toString():String {
       if ( re == 0.0 ) return if ( im == 0.0 ) "0" else "${im}i"
       return if ( im == 0.0 ) "$re" else
                   if ( im > 0.0 ) "${re} + ${im}i" else "${re} - ${-im}i"
   }

   //重寫equals方法 因爲浮點有-0 +0的區別 所以用equals
   override fun equals(other: Any?) = when (other) {
                                           !is Complex -> false
                                           else -> this === other ||
                                                    re == other.re && im == other.im
                                       }
   //因爲Double有-0.0 < +0.0 問題,按照一般原則,兩個對象相等, 它們的hashcode也要相等                                
   override fun hashCode()= 31*( if (re.equals(-0.0)) 0.0 else re ).hashCode() + ( if (im.equals(-0.0)) 0.0 else im ).hashCode()
}
   

fun main() {
   val d1=-0.0
   val d2=0.0
   println("d1=d2:${d1==d2}")
   println("d2==-0.0:${d2.equals(-0.0)}")
   println("d1==-0.0:${d1.equals(-0.0)}")
     println("d1=d2:${d1.compareTo(d2)}")
   println(d1.hashCode())
   println(d2.hashCode())
   val c1 = Complex(1.0, 1.0)
   val c2 = Complex(1.0, 2.0)
   val c3=Complex(3,-2)
   val c4=Complex(0.0,0.0)
   val c5=Complex(0,2.0)
   val c6=Complex(3.0,0)
   println(c1)
   println(c2)
   println(c3)
   println(c4)
   println(c5)
   println(c6)
   println("-----------")
   val c7=Complex(+0.0,+0.0)
   val c8=Complex(-0.0,-0.0)
   println(c7)
   println(c8)
   val c9=Complex(3,0)
   val c10=Complex(3.0,-0.0)
   val c11=Complex(3.0,+0.0)
   
   println("c1==c2: ${c1 == c2}")
   println("c7==c8: ${c7 == c8}")
   println("c9==c10: ${c9 == c10}")
   println("c11==c10: ${c11 == c10}")
   println("c1.hashcode=${c1.hashCode()}")
   println("c7.hashcode=${c7.hashCode()}")
   println("c8.hashcode=${c8.hashCode()}")
   println("c9.hashcode=${c9.hashCode()}")
   println("c10.hashcode=${c10.hashCode()}")
   println("c11.hashcode=${c11.hashCode()}")
   
   println("c2+c1=${c2+c1}")
   println("c1-c2=${c1-c2}")
   println("c1*c2=${c1*c2}")
   println("c2/c1=${c2/c1}")
   val c12=Complex()
   println("c1/c12=${c1/c12}")
   println(c1.modulus())


   // copy() function
   println(c1.copy())                      
   println(c1.copy(re=0.0))      
   println(c1.copy(im = 2.1))              
   
   println("re = ${c1.component1()}")                
   println("im = ${c1.component2()}")
}

運行結果:
d1=d2:true
d2==-0.0:false
d1==-0.0:true
d1=d2:-1
-2147483648
0
1.0 + 1.0i
1.0 + 2.0i
3.0 - 2.0i
0
2.0i
3.0
-----------
0
0
c1==c2: false
c7==c8: true
c9==c10: true
c11==c10: true
c1.hashcode=-33554432
c7.hashcode=0
c8.hashcode=0
c9.hashcode=-1057488896
c10.hashcode=-1057488896
c11.hashcode=-1057488896
c2+c1=2.0 + 3.0i
c1-c2=-1.0i
c1*c2=-1.0 + 3.0i
c2/c1=1.5 + 0.5i
c1/c12=NaN - NaNi
1.4142135623730951
1.0 + 1.0i
1.0i
1.0 + 2.1i
re = 1.0
im = 1.0

2:未改進的,偏java寫法

data  class  datacomplex(val real: Double,val image: Double) { //數據型data 複數類

    //fun copy(real:Double = this.real, image:Double = image) = datacomplex(real, image)


    internal fun add(a: datacomplex):datacomplex { // 1複數相加
        val real2 = a.real
        val image2 = a.image
        val newReal = real + real2
        val newImage = image + image2

        var result:datacomplex=datacomplex(newReal,newImage)
        return result
    }

    internal fun sub(a: datacomplex): datacomplex { //2 複數相減
        val real2 = a.real
        val image2 = a.image
        val newReal = real - real2
        val newImage = image - image2

        var result:datacomplex=datacomplex(newReal,newImage)
        return result
    }

    internal fun mul(a: datacomplex): datacomplex { //3 複數相乘
        val real2 = a.real
        val image2 = a.image
        val newReal = real * real2 - image * image2
        val newImage = image * real2 + real * image2

        var result:datacomplex=datacomplex(newReal,newImage)
        return result
    }

    internal operator fun div(a: datacomplex):datacomplex { //4 複數相除
        val real2 = a.real
        val image2 = a.image
        val newReal = (real * real2 + image * image2) / (real2 * real2 + image2 * image2)
        val newImage = (image * real2 - real * image2) / (real2 * real2 + image2 * image2)

        var result:datacomplex=datacomplex(newReal,newImage)
        return result
    }

    internal fun mod(a: datacomplex):datacomplex { //5 複數模運算
        val real2 = a.real
        val image2 = a.image
        val newReal = (real * real2 + image * image2) +(real2 * real2 + image2 * image2)
        val newImage = (image * real2 - real * image2) + (real2 * real2 + image2 * image2)
        var result:datacomplex=datacomplex(newReal,newImage)
        return result
    }

 


//6toString打印方法

    override fun toString(): String {
        return "當前運算(實部=$real, 虛部=$image)"
    }


}

//主函數入口

fun main(args: Array<String>){
    println("請用戶輸入第一個複數的實部和虛部:2.0  4.0")
    val data1 = datacomplex(2.0,4.0)
    println("請用戶輸入第二個複數的實部和虛部:3.0  5.0")
    val data2 = datacomplex(3.0,5.0)

    // 以下分別爲加減乘除
    val result_add: datacomplex = data1.add(data2)
    val result_sub = data1.sub(data2)
    val result_mul = data1.mul(data2)
    val result_div = data1.div(data2)
    val result_mod = data1.mod(data2)

 

    println("data類複數相加"+result_add.toString())
    println("data類複數相減"+result_sub.toString())
    println("data類複數相乘"+result_mul.toString())
    println("data類複數相除"+result_div.toString())
    println("data類複數相除"+result_mod.toString())


    val resultcopy: datacomplex = data1.copy(real = 2.0)//data類copy函數調用
    println("copy函數測試"+resultcopy.toString())
    if (resultcopy.equals(data1))
        println("兩個對象相等,copy成功" )


    println("解析函數componentN()用於數據類解析聲明")//Component函數在解構聲明中使用
    val testcomponentN = datacomplex(real=3.5, image=2.4)
    val (realtc, imagetc) = testcomponentN///編譯器處理:val name=jane.Component1()  val age=jane.Component2()
    println("realtc = $realtc,imagetc=$imagetc")//real=3.5, image=2.4

}

 

運行結果

請用戶輸入第一個複數的實部和虛部:2.0  4.0
請用戶輸入第二個複數的實部和虛部:3.0  5.0
data類複數相加當前運算(實部=5.0, 虛部=9.0)
data類複數相減當前運算(實部=-1.0, 虛部=-1.0)
data類複數相乘當前運算(實部=-14.0, 虛部=22.0)
data類複數相除當前運算(實部=0.7647058823529411, 虛部=0.058823529411764705)
data類複數相除當前運算(實部=60.0, 虛部=36.0)
copy函數測試當前運算(實部=2.0, 虛部=4.0)
兩個對象相等,copy成功
解析函數componentN()用於數據類解析聲明
realtc = 3.5,imagetc=2.4

859個字
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章