iT邦幫忙

2021 iThome 鐵人賽

DAY 9
0
Mobile Development

Kotlin Android 30天,從 0 到 ML (Machine Learning)系列 第 9

Kotlin Android 第9天,從 0 到 ML - 介面與抽象類別 / 泛型 / 擴充

前言:

   今天來看 介面與抽象類別 / 泛型 / 擴充

大綱:

Interface 介面,像是一個SOP或是流程, 大家使用後都一定要照著SOP/流程自己實作一次

var mIronPlayer = ironPlay("Kotlin Android 30天,從 0 到 ML")
mIronPlayer.showTitle()

var mWebinarSpeaker = webinarSpeaker("Kotlin Android 30天,從 0 到 ML 參賽心得")
mWebinarSpeaker.showTitle()

// Interface like SOP or flow
interface TitleInterface{
    fun showTitle()
}

class ironPlay(title:String):TitleInterface{
    var mTitle = title
    override fun showTitle() {
        //TODO("Not yet implemented")
        println("ironPlay Tilte = $mTitle")
    }

}

class webinarSpeaker(title:String):TitleInterface{
    var mTitle = title
    override fun showTitle() {
        //TODO("Not yet implemented")
        println("webinarSpeaker Tilte = $mTitle")
    }

}

https://ithelp.ithome.com.tw/upload/images/20210914/20121643oK8M3lRuap.png

abstract class(抽象類別) 不能直接被實例化,只能被類別繼承。

var mWebSpeaker = webSpeaker("Kotlin Android 30天,從 0 到 ML 辛苦談")
mWebSpeaker.showTitle()

abstract class seminarSpeakers (title:String){
    abstract fun showTitle()
}

class webSpeaker(title:String): seminarSpeakers(title) {
    var mTitle = title
    override fun showTitle() {
        //TODO("Not yet implemented")
        println("abstract Tilte = $mTitle")
    }
}

https://ithelp.ithome.com.tw/upload/images/20210914/20121643g9RJ2hP08A.png

擴充,不想用繼承或是直接修改類別的話,可以使用擴充,通常用 T 來代表全部物件

var mAnySpeaker = anySpeaker(1234 )
mAnySpeaker.showTitle()

anyEventSpeaker(123456)
anyEventSpeaker("Kotlin Android 30天,從 0 到 ML 談天說地")

println("Extensions Speaker Name = "+mWebSpeaker.getSpeakerName())

//Generic Classes
class anySpeaker<T>(title:T) {
    var mTitle = title
    fun showTitle() {
        //TODO("Not yet implemented")
        println("Generic class Tilte = $mTitle")
    }
}

//Generic fun
fun <T> anyEventSpeaker(title:T) {
        println("Generic fun Tilte = $title")
}

//擴充 Extensions
fun webSpeaker.getSpeakerName() = "Kevin"

執行結果:
https://ithelp.ithome.com.tw/upload/images/20210914/20121643I2C1y6cBZP.png

參考:

https://kotlinlang.org/docs/interfaces.html
https://kotlinlang.org/docs/generics.html#declaration-site-variance


上一篇
Kotlin Android 第8天,從 0 到 ML - 定義類別 / 初始化 / 繼承
下一篇
Kotlin Android 第10天,從 0 到 ML - Kotlin 與 Java 互動操作
系列文
Kotlin Android 30天,從 0 到 ML (Machine Learning)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言