본문으로 바로가기

Kotlin Migration Check List

category 개발삽질방/Android 2019. 10. 28. 10:09
반응형

UI Component 초기화

일반적으로 안드로이드 스튜디오에서 제공하는 자바-코틀린 변환 툴을 쓰면 UI Component를 두 가지의 방식으로 컨버팅 한다

//Type 1
private tvTest:TextView? = null

//Type 2
private lateinit tvTest

두 개 중 어느 것이 맞는 것일까?

Type 1의 경우에는 사실상 null이 허용되는 객체가 되어버리므로 코틀린의 Null-safety 정책(NullPointerException의 제거)에 어긋난다.

tvText!!.setText = "Text"

!! 연산자를 사용하게 됨으로써 NullPointerException의 발생 가능성이 있다

따라서 Type 2의 방법으로 UI 컴포넌트를 초기화해주는 것이 맞다

참고 : What is the best way to declare on UI component in android with Kotlin?

 

What is the best way to declare on UI component in android with Kotlin?

I'm trying to build android application using Kotlin for the first time. I want to declare on some buttons outside the OnCreate method and i can initialize them only Inside this function with

stackoverflow.com

 

Replaceable with operator-assignment

Kotlin으로 변환 후 기존의 코드 일부에서 경고 표시가 나는 부분이 있다

mPage = mPage + 1

이렇게 일부 연산자가 사용된 곳에서 경고 표시가 나는데 이 부분이 코틀린에서는 간략하게 변경되었고 그렇게 사용하는것을 추천하기 때문이다.

mPage++

다음과 같이 변경하였다

아래 링크에서 더 많은 연산자 형태를 볼 수 있다.

참고 : Kotlin Operator-Assignment

 

Kotlin Operator-Assignment

I've noticed some funny behavior with the Kotlin Operator-Assignment var selectedIndex = 0 selectedIndex += selectedIndex upon debugging, selected index still equals 0 When changed to selectedI...

stackoverflow.com

 

Kotlin Inner Class

기본적으로 자바에서는 Class 안에 Class를 쓰면 자동적으로 해당 클래스는 Inner Class로 간주한다.

하지만 코틀린에서는 Class 안에 Class를 써도 독립된 Class로 처리한다.

따라서 코틀린에서는 다음과 같이 Inner Class라는 것을 따로 명시해야 한다.

inner class NewsListAdapter(val context: Context) : RecyclerView.Adapter<NewsListAdapter.Holder>() {
    //Override Methods
}

 

Use of set method instead of property access syntax

구글은 예전에도 POJO 등의 클래스에서 Get/Set Method를 만들지말고 변수를 Public 처리하는 것을 추천했었다.

코틀린에서는 아예 Get/Set 메소드를 자동 생성한다.

기존에는

mRecyclerView.setLayoutManager(layoutManager)

이런식으로 사용하던 것을

mRecyclerView.layoutManager = layoutManager

이런식으로 써야 경고가 사라진다.

 

코틀린의 접근 제한자(캡슐화)

private: 이 요소는 외부에서 접근할 수 없다

public: 이 요소는 어디서든 접근이 가능하다(기본값)

protected: 외부에서 접근할 수 없으니 하위 상속 요소에서는 가능하다

internal: 같은 정의의 모듈 내부에서는 접근이 가능하다

반응형