TIL 220614

박수빈·2022년 6월 14일
0

TIL

목록 보기
23/25

이것이 안드로이드다

1-3. 코틀린 사용을 위한 기본 문법

4. 배열과 컬렉션

모든 결과가 [1,2,3] 으로 출력됨 (대괄호)

배열

  • 처음에 크기 지정
var intArr = IntArray(10)
  • String 어레이
var strArr = Array(10, {item -> ""})
var strArr = arrayOf("ABC", "def")
  • 값 할당 [], .set()
  • 값 가져올 때 [], .get()

컬렉션 Collection

  • 동적 배열
  1. List
    var list = mutableListOf("a", "b", "c")
    list.add("d")
    list.get("1") // b
    list.set(1, "e") // (a,e,c,d)
    list.removeAt(1) // (a,c,d)
    list.size // 3. property
    
    var strList = mutableListOf<String>() // 이런 경우 generic 필수
  1. Set
	var set = mutableSetOf<String>()
    set.add("a")
    set.remove("a")
    // 인덱스 접근, 개별 출력 불가
  1. Map
	var map = mutableMapOf<String, String>()
    map.put("키1", "값1") // 수정도 같은 방법
    map.get("키1") // 값1
    map.remove("키1")
    // 없는 값 출력시 null

immutable collection

var list = listOf(1,2)
  • immutable 이라서 set, get 불가능
  • array는 값 변경은 되지만, immutable은 값 변경도 불가능

5. 반복문

// 10 포함
for (i in 1..10){
	println(i)
}

// 10 불포함
// until array.size 로 많이 사용
for (i in 1 until 10) {
	println(i)
}

for (i in 1 until 10 step 3)
for (i in 0 downTo 10)

//while
while (조건) {
}

do {
	print("do 구간")
} while (조건)

6. 함수

fun 함수명(파라미터 이름: 타입): 반환 타입 {
	return}
  • 함수의 파라미터는 모두 immutable, 즉 val 상수

7. 클래스와 설계

class 클래스명 {
	var 변수 // member var, property
    init {
    	// 기본 생성자
    }
    // member funciton, method
    fun 함수() {
    	// 코드
    }
}

primary constructor

class 클래스명 constructor (value: type) {
}

class 클래스명 (value: type) {
}

class 클래스명 (value: type) {
	init {
    	// primary const가 실행될 때, 실행될 코드
    }
}

secondary constructor

class 클래스명 {
	constructor (value: type) {
    	// 코드
    }
}
  • 하나 이상 가능
  • init가 더 우선됨

companion object

  • 클래스를 인스턴스화 하지 않고 사용
  • static
class ktClass {
	companion object {
    	var one: String = "None"
        fun printOne() {
        	println(one)
         }
    }
}

// 클래스명으로 호출
KtClass.one = "new val"
KtClass.printOne()

data class

data class 클래스명 (val 파라미터: 타입, var 파라미터: 타입)

dataClass.copy() // 복사

상속

open class 부모 {}
class 자식 (value: String) : 부모(value) {}

class CustomView : View { // 세컨더리 생성자 이용 -> () 생략
	constructor(ctx: Context): super(ctx) // 부모 클래스로 전달
}
  • open 키워드가 붙은 부모 메서드를 자식이 override로 상속
  • proprty도 마찬가지

abstract
자식이 갖을 법한 method, property
method 자세히 구현 가능

inteface
이름만 가진 abstract

접근 제한자

  • private
  • internal: 같은 모듈
  • protectedd: private이나, 자식 클래스는 접근
  • public

generic

  • 입력 값의 타입 자유롭게 사용
public interface MutableList<E> {
	var list: Array<E>
}

Null Safety

Nullable

	var variable: String? // 변수 사용시 null 체크가 필수적

안전한 호출 safe call ?.

	// str이 null 이면 null 반환
    var resultNull: Int? = str?.length

null 값 대체 ?:

// elvis op
var resultNonNull: Int = str?.length?:0
profile
개발자가 되고 싶은 학부생의 꼼지락 기록

0개의 댓글