[Android App] Kotlin

z00m__in·2021년 8월 3일
0

0. Android Studio 입문

1) Template

  • Phone and Tablet
  • Wear OS
  • Android TV
  • Automotive

2) Project

  • Name: 어플리케이션의 이름 (변경 가능)
  • Package name: 앱과 앱을 구분하는 이름 -> 전 세계에 고유해야 함
  • Minimum API level: 운영체제 선택 가능

3) Device

i. 가상 핸드폰

상단의 No device > APL > Create Virtual Device > Phone > Pixel 3 XL

  • 제품 선택 (화면 크기 고려)
  • OS 버전 선택 (Marshmallow)
  • 가로, 세로모드 선택
  • Network: 인터넷 속도에 따른 작동 결과 확인 가능

ii. 실제 핸드폰

개발자 모드로 변경 후 노트북과 연결 (USB 디버깅)

2. Kotlin 문법

1) 변수

i. 변수 종류

  • var: 원하는 것을 임의로 아무거나 넣을 수 있는 변수
  • val: 한 번 넣으면 바꿀 수 없는 변수

ii. 변수 선언 방식

var/val 변수명 = 값

var num = 10
var hello = "hello"
var point = 3.4

var/val 변수 : 자료형 = 값

var number1: Int = 20
var hello1: String = "Hello"
var point1: Double = 3.4

2) 자료형

  • 정수형: Long > Int > Short > Byte
  • 실수형: Double > Float
  • 문자: Char
  • 문자열: String
  • 논리형: Boolean

3) 메소드(함수)

: input에 따른 output을 배출하는 것

i. 함수 선언 방식

fun 함수명(변수명:타입, 변수명:타입, ... ) : 반환형 {
함수내용
return 반환값
}

fun plus(first: Int, second: Int): Int {
    println(first)
    println(second)
    val result: Int = first + second
    println(result)
    return result
}

변형 - 디폴트값을 갖는 함수

fun plusFive(first: Int, second: Int = 5): Int {
    val result: Int = first + second
    return result
}

변형 - 반환값이 없는 함수

fun printPlus(first: Int, second: Int): Unit {
    val result: Int = first + second
    println(result)
}

변형 - 간단한 함수 선언

fun plusShort(first: Int, second: Int) = first + second

변형 - 가변인자를 갖는 함수 (여러개의 변수)

fun plusMany(vararg numbers: Int) {
    for (number in numbers) {
        println(number)
    }
}

ii. main 함수

: 프로그램을 실행할 때 가장 먼저 돌아가는 함수 - 필수

4) 연산자

i. 산술연산자

: +, -, *, /(몫 구하기), %(나머지 구하기)

ii. 대입연산자

: =

iii. 복합대입연산자

: +=, -=, *=, /=, %=

iv. 증감연산자

: ++, --

v. 비교연산자

: >, >=, <, <=, ==, !=

vi. 논리연산자

: &&, ||, !

5) 제어흐름

i. if-else

: JAVA 및 C와 유사

ii. when

: C의 switch와 유사
-> 변수의 값이 무엇인지에 따라 다른 명령을 수행하는 것

when (value) {
        null -> println("value is null")
        else -> println("value is not null")
    }
    
    // value의 값이 null 인지 아닌지를 판단
    when (value) {
        in 60..70 -> {
            println("value is in 60-70")
        }
        in 70..80 -> {
            println("value is in 70-80")
        }
        in 80..90 -> {
            println("value is in 80-90")
        }
    }
    // 값이 어느 구간 내에 있는지를 판단

6) 배열

i. 배열을 생성하는 방법

var number: Int = 10
    var group = arrayOf<Int>(1, 2, 3, 4, 5)
    println(group1 is Array)
 var number = 10
    var group = arrayOf(1, 2, 3.5, "Hello")

ii. 배열의 값에 접근하는 방법

값 꺼내기

  • 그냥 index를 사용해 값을 가져오기
  • get 메소드를 사용해 값을 가져오기
//index를 사용해 0번 index의 값을 가져오기
val test = group.get(0)

//get 메소드를 사용해 0번 index의 값을 가져오기
val test = group[0]

값 바꾸기

  • 그냥 index를 사용해 값을 바꾸기
  • set 메소드를 사용해 값을 바꾸기
//index를 사용해 0번 index의 값을 100으로 바꾸기
group[0] = 100

//set 메소드를 사용해 0번 index의 값을 100으로 바꾸기
group.set(0, 100)

7) Collection

: 기본적인 개념은 모두 JAVA와 유사
-> 변경이 불가능한 Immutable Collection이 기본이며, 변경이 가능한 Mutable Collection은 따로 존재 (JAVA의 Collection은 mutable 형태)

i. List

: 중복 허용, 순서O

  • size : list의 크기를 리턴하는 중요 메소드

Immutable List

val numberList = listOf<Int>(1, 2, 3, 3)
    println(numberList)
    println(numberList.get(0))
    println(numberList[0])
    
    //Immutable 형태이므로 get만 가능

Mutable List

    val mNumberList = mutableListOf<Int>(1, 2, 3)
    mNumberList.add(3, 4)
    println()
    println(mNumberList)

ii. Set

: 중복 허용X, 순서X

Immutable Set

val numberSet = setOf<Int>(1, 2, 3, 3, 3)
    println()
    numberSet.forEach {
        println(it)
    }

Mutable Set

    val mNumberSet = mutableSetOf<Int>(1, 2, 3, 4, 4, 4)
    mNumberSet.add(10)
    println(mNumberSet)

iii. Map

: Key와 Value의 쌍으로 관리

Immutable Map

    val numberMap = mapOf<String, Int>("one" to 1, "two" to 2)
    println()
    println(numberMap.get("one"))

Mutable Map

    val mNumberMap = mutableMapOf<String, Int>("one" to 1)
    mNumberMap.put("two", 2)
    println(mNumberMap)

8) 반복문

: 주로 for문 사용

i. List의 메소드 사용

forEach

: 특정 list의 모든 값에 따라 같은 명령문 반복

val a = mutableListOf<Int>(1, 2, 3, 4, 5, 6, 7, 8, 9)
a.forEach { item ->
   //현재 반복문이 돌고있는 a의 값을 item이라는 변수에 넣겠다는 의미
        println(item)
    }

forEachIndexed

: 특정 list를 돌면서 index의 값까지 받는 경우

val a = mutableListOf<Int>(1, 2, 3, 4, 5, 6, 7, 8, 9)
a.forEachIndexed { index, item ->
        println("index : " + index + " value : " + item)
    }

ii. for문 사용

for (변수 in 시작 until 끝 step (건너뛰는 단계)){}
+++ (step은 생략 가능)

//한 단계씩 올라갈 때
for (i in 0 until a.size) {
        println(a.get(i))
    }

//step 사용해 두 단계씩 올라갈 때
for (i in 0 until a.size step (2)) {
        println(a.get(i))
    }

for (변수 in 끝 downTo (시작) step (건너뛰는 단계)){}
+++ 끝에서부터 내려올 때

//한 단계씩 내려올 때
for (i in a.size - 1 downTo (0)) {
        // 8 부터 0 까지 반복
        println(a.get(i))
    }
    
//step 사용해 두 단계씩 내려올 때
for (i in a.size - 1 downTo (0) step (2)) {
        println(a.get(i))
    }

for (변수 in 시작..끝){}

for (i in 0..a.size) {
        // .. -> 마지막을 포함한다
        println(i)
    }

iii. while문 사용

: break를 통해 제어

9) 클래스

: JAVA에서와 유사 - 객체지향 프로그래밍

i. 클래스 생성 형태

생성자 포함

class Car constructor(engine: String, body: String) {
    var door: String = ""

    constructor(engine: String, body: String, door: String) : this(engine, body) {
        this.door = door
    }
}

속성 포함

class Car1 {
    var engine: String
    var body: String
    var door: String

    constructor(engine: String, body: String, door: String) {
        this.engine = engine
        this.body = body
        this.door = door
    }
}

메소드 포함

class Car3 {
    var engine: String
    var body: String

    constructor(engine: String, body: String) {
        this.engine = engine
        this.body = body
    }

    init {
        // 초기셋팅을 할 때 유용하다
        println("RunableCar2가 만들어 졌습니다")
    }

    fun ride() {
        println("탑승 하였습니다")
    }

    fun drive() {
        println("달립니다 !")
    }

    fun navi(destination: String) {
        println("$destination 으로 목적지가 설정되었습니다")
    }
}

오버로딩

class TestClass() {

    fun test(a: Int) {
        println("up")
    }

    fun test(a: Int, b: Int) {
        println("down")
    }
}
profile
우당탕탕 기록지

0개의 댓글