[요약] interface, operator, 컬렉션

pge87132·2023년 9월 21일

Kotlin 문법

목록 보기
3/4
post-thumbnail

interface

  • 자바와 다르게 구현부가 있는 함수를 정의할 수 있다
  • 프로퍼티에 값을 저장할 수 없다
interface Walker {
	val stepCount: Int   // val stepCount = 0 X
    fun addStepCount()
}
  • 클래스를 상속할 경우 1개의 클래스만 상속할 수 있지만 인터페이스는 상속 갯수에 제한이 없다
interface Clickable {
	fun showOff() = Log.d("Clickable showoff")
}

interface Focusable {
    fun showOff() = Log.d("Focusable showoff")
}
    
class Button : Clickable, Focusable {
    override fun showOff() {
    	super<Clickable>.showOff()
    	super<Focusable>.showOff()
    }
}

visibility modifier

  • 클래스의 가시성 변경자
    modifierscope
    public기본값. 어느 위치에서든 참조 가능
    private선언한 클래스 내부에서만 참조 가능
    internal같은 module 안에서만 참조 가능
    protectedprivate과 동일 + subclass 에서는 참조 가능
abstract class Screen {
	protected abstract fun setLayout()
}
    
class HomeScreen : Screen() {
    override fun setLayout() {
    	val movieList = getMovieList()
   	}
}
    
class App {
    val home = homeScreen()
    		
    fun setLayout() {
    	home.setLayout()      // 불가능
    }
}
  • 최상위 선언에서의 가시성 변경자
    modifierscope
    public기본값. 어느 위치에서든 참조 가능
    private선언한 file 내부에서만 참조 가능
    internal같은 module 안에서만 참조 가능

const

  • 컴파일 시점에 값을 할당한다
  • 할당 가능한 타입 : 기본 타입, String
const val TAG = "MainActivity"

operator

  • safe call operator ?.
    • non-null 일 때만 호출한다
var userName: String? = null
val result = userName?.isEmpty()
if (result == true) {
	println("사용자 이름을 설정해주세요")
}
  • elvis operator ?:
    • ?: 의 왼쪽 객체가 non-null이면 객체의 값을 반환하고 null 이면 오른쪽 값을 반환한다
fun main() {
	val userName = readLine() ?: ""
	if (userName.isEmpty()) {
		println("사용자 이름을 설정해주세요")
	} else {
		println("${userName}님, 안녕하세요!")
	}
}
  • not-null assertion operator !!
    • nullable로 설정된 프로퍼티를 강제로 not null로 변환한다
    • NPE 가 발생할 가능성이 있다
  • type check is, !is
    • 타입을 검사할 수 있다
    • smart cast
      • 객체가 타입의 조건을 만족하면 컴파일러가 자동으로 캐스팅 해주는 기능
fun saveData(input: Any) {
	if (input is String) {
    	print(input.length)
    }
}
  • type cast operator as, as?
    • as
      • unsafe cast operator
      • 타입 변환에 실패하면 예외가 발생한다
    • as?
      • safe cast operator
      • 타입 변환에 실패하면 null을 반환한다

컬렉션

  • 같은 타입의 여러 객체를 저장하고 관리하기 위해 설계된 자료구조
  • list
    • 순서가 있는 데이터의 집합
    • 인덱스로 요소에 접근할 수 있다
  • set
    • 중복을 허용하지 않는 데이터의 집합
    • 코틀린의 set은 순서가 유지된다
  • map
    • key-value 쌍으로 이루어진 자료구조
    • key는 고유한 값을 가진다
profile
처음 읽는 누구나 이해할 수 있도록 쓰자

0개의 댓글