코틀린

[Youtube DiMo] 16강. Object

iseohyun 2022. 4. 29.

목차

    [16강] https://youtu.be/QPqzmKu0Y_k

     

    1. object (소문자/클래스 아님)

    object = Singleton Patton 또는 Static Var에 해당
    fun main() {
        println(myObj.score)
        myObj.plus(10)
        println(myObj.score)
    }
    
    object myObj{
        var score = 0
        fun plus(x : Int) { score += x }
    }
    0
    10

     

     

    2. companion object

    fun main() {
        var a = menu("짜장")
        var b = menu("짬뽕")
        
        a.vote()
        a.vote()
        a.vote()
        
        b.vote()
        b.vote()
        
        println("${a.name} : ${a.count}")
        println("${b.name} : ${b.count}")
        println("총계 : ${menu.total}")
    }
    
    class menu(val name : String) {
        companion object {
            var total = 0
        }
        
        var count = 0
        
        fun vote() {
            count++
            total++
        }
    }
    짜장 : 3
    짬뽕 : 2
    총계 : 5

    댓글