코틀린은 static이 존재하지 않는다. 따라서 static을 사용하기 위해선 object로 선언해야한다.

 

1. 일반 객체 선언

  • 일반 객체 선언은 보통 싱글톤으로 이용이 가능하다.
  • 클래스 선언과 그 클래스에 속한 단일 인스턴스 생성을 동시에 처리한다.
  • 보통의 클래스처럼 다른 클래스와 인터페이스의 상속이 가능하다.
  • property, method, init 선언이 가능하다.

 

- companion object

  • 코틀린은 한 클래스 내에 inner와 object를 동시에 구현할 수 없다. 클래스 안에 들어있는 객체 선언일지라도 바깥 클래스 멤버에 그냥 접근할 수 없다.

  • 하지만 객체를 생성하면서 접근하는 방법은 가능하다. private 생성자를 object 내에서 호출할 수 있어 팩토리 메소드 패턴을 구현하기 적합하다.

  • 클래스 안에 중첩 클래스로 object가 들어가는 경우 앞에 companion을 붙이면 object의 이름을 명시하지 않고 바깥 클래스의 이름으로 바로 접근할 수 있다.

  • 호출 : 클래스.메소드이름()

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Companion object가 선언된 팝업 클래스
class _Popup {
    companion object {
        private val mInstance = _Popup()
        fun GetInstance(): _Popup {
            return mInstance
        }
    }
           fun ShowConfirmPopup(context: Context, title: String?, mainMessage: String?, confirmMessage: String) {
        mConfirmAlt_Builder = AlertDialog.Builder(context)
        if (title != null) mConfirmAlt_Builder.setTitle(title)
        if (mainMessage != null) mConfirmAlt_Builder.setMessage(mainMessage)
        mConfirmAlt_Builder.setCancelable(false)
        mConfirmAlt_Builder.setPositiveButton(confirmMessage) { dialog, id ->
            if (confirmPopupListener != null) confirmPopupListener.didSelectConfirmPopup(title, mainMessage, confirmMessage)
            binaryPopupListener = nul
            mBinaryAlt_Builder = null
            dialog.cancel()
        }
        val mmAlert = mConfirmAlt_Builder.create()
        mmAlert.show()
    }
}
// 버튼을 누르면 팝업을 불러오는 액티비티 클래스
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        temp_button.setOnClickListener {
            _Popup.GetInstance().ShowBinaryPopup(
                    this,
                    "앱을 종료하시겠습니까?",
                    "종료",
                    "취소",
                    object : _Popup.BinaryPopupListener {
                        override fun didSelectBinaryPopup(mainMessage: String, selectMessage: String) {
                            if (selectMessage == "종료") {
                                exitApp()
                            } else {
                                return
                            }
                        }
                    })
        }
    }
    // 앱 종료하는 메소드
    private fun exitApp() {
        this.finish()
    }
}
cs

 

 

  • 결과 화면

 

참조 : https://umbum.tistory.com/597

'개발 > Kotlin' 카테고리의 다른 글

[Kotlin] val, var  (0) 2019.04.21

+ Recent posts