Generic > IT 기술백서

IT 기술백서

직접 알아내거나 검색하기 귀찮아서 모아 둔 것

Android | Generic

본문

class 생성자에서  Generic 사용하기 

class ClassName<T[:Type]> (val t: T) {

  ...

}

 

function 에서 Generic 사용하기

fun <t[:Type]> FunctionName (t: T) {

  ...

}

 

사용예 

[code]

 

 

fun main() {

    println("-- class contructor --")

    UsingGeneric(A()).doShouting()

    UsingGeneric(B()).doShouting()

    UsingGeneric(C()).doShouting()

    

    println("-- function --")

    doShouting(A())

    doShouting(B())

    doShouting(C())

}


fun <T: A>doShouting(t: T) {

    t.shout()

}


open class A {

    open fun shout() {

        println("A가 소리칩니다")

    }

}


class B: A() {

    override fun shout() {

        println("B가 소리칩니다")

    }

}


class C: A() {

    override fun shout() {

        println("C가 소리칩니다")

    }

}


class UsingGeneric<T: A>(val t: T) {

    fun doShouting() {

        t.shout()

    }

}

[/code]

댓글 0개

등록된 댓글이 없습니다.

Menu