컴굥일지

[Kotlin] 코틀린 기초 더 배우기 본문

프로그래밍 강의/Kotlin

[Kotlin] 코틀린 기초 더 배우기

gyong 2022. 12. 28. 23:06
반응형

코틀린 기초 더 배우기

배열

  • 한 개의 변수에 여러 가지 데이터를 저장
fun main() {
    val numbers:IntArray = intArrayOf(1,2,3,4,5,6)
    val numbers2= intArrayOf(1,2,3,4,5,6) //타입 추론
    val numbers3= arrayOf(1,2,3,4,5,6) //이렇게만 써도 됨
    println(numbers3) // 배열의 주소가 출력된다.
    print(numbers3.contentToString()) // 내용을 스트링으로 바꾸어준다
    println()
    for (element in numbers3){
        print("${element+2} ") //이런다고 number3가 바뀌진 않는다
    }
    println()
    println(numbers3[0]) //인덱스는 0번부터 시작
    numbers3[0]=300
    println(numbers3[0])
    //numbers3[6]=233  <-- out of bound
    val days= arrayOf("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
    println(days.contentToString())
    //배열에 객체를 저장할 수도 있음
    val fruit= arrayOf(Fruit("Apple",2.5), Fruit("Grape",3.5))
    println(fruit.contentToString())
    println(fruit[1].name)
    for(index in fruit.indices){ //fruit의 인덱스를 반환한다
        println("${fruit[index].name} is in index $index")
    }
    for(f in fruit){
        println(f.price)
    }
    // arrayOf는 다양한 데이터 타입을 쓸 수 있다.
    val mixed= arrayOf("Sun","Mon","Tue",1,2,3,"Sat",3.5,6.4F,Fruit("Grape",3.5))
    println(mixed.contentToString())
}
data class Fruit(val name:String, val price:Double)

리스트

  • 배열과 비슷하지만 크기가 바뀔 수 있다는 특징이 있다.
  • 또한 수정할 수 있는 mutable 타입과, 수정 불가능한 읽기 타입의 immutable 타입이 있다.
fun main() {
    val months= listOf("Jan", "Feb","March") // immutable함
    val anyTypes=listOf(1,2,3, true, "string") //아무 타입이나 사용 가능
    println(anyTypes.size) //크기 출력
    println(anyTypes[4])
    for (item in months)
        print("$item ")
    println()
    val additionalMonths=months.toMutableList() //이제 추가 가능
    val newMonths = arrayOf("April","May","June")
    additionalMonths.addAll(newMonths)
    println(additionalMonths) //리스트는 배열과 달리 그냥 출력해도 됨
    additionalMonths.add("July")
    println(additionalMonths)
    additionalMonths.removeLast()
    println(additionalMonths)
    val days= mutableListOf<String>("Sun","Mon","Tue","Wed","Thu","Fri","Sat") //특정 타입의 뮤터블 리스트를 만드는 경우
    println(days)
    days.removeAt(3)
    days[0]="HAHAHAHA"
    println(days)
    val removeList= listOf<String>("Mon","Sun") //여기가 list나 mutable list나 상관 없음
    days.removeAll(removeList) //Sun은 어차피 없어서 못 지움
    println(days)
    days.removeAll(days) //전체 삭제
    println(days)
}

집합과 맵

  • 집합(set) : 중복되는 데이터를 삭제하는 컬렉션. 정렬이 안된다는 특징이 있다.
    • immutable : setOf
    • mutable : mutableSetOf
    • hashSetOf
  • 맵(map) : 키와 값을 짝 형태로 데이터를 저장하는 컬렉션. 키는 unique하고 하나의 값만을 저장할 수 있다.
fun main() {
    val fruits = setOf("Orange", "Apple", "Grape", "Apple") //중복 제거
    println(fruits.size)
    println(fruits)
    println(fruits.toSortedSet()) //알파벳 순으로 정렬
    val newFruits = fruits.toMutableList()
    newFruits.add("Water Melon")
    newFruits.add("Mango")
    newFruits.add("Apple")
    println(newFruits)
    println(newFruits.elementAt(4))
    val againFruits = newFruits.toMutableSet()
    println(againFruits)
    // map - 다른 언어에서는 hash map이나 dictionary로 불리기도 한다
    val daysOfTheWeek = mapOf(1 to "Monday", 2 to "Tuesday", 3 to "Wednesday", 4 to "HELLO")
    println(daysOfTheWeek[2]) //인덱스가 아닐 key임
    for (key in daysOfTheWeek.keys)
        print("$key is to ${daysOfTheWeek[key]} || ")
    println()
    val fruitsMap = mapOf("Favorite" to Fruit("Grape", 2.5), "Ok" to Fruit("Mango", 4.6))
    val newDayOfWeek = daysOfTheWeek.toMutableMap()
    newDayOfWeek[4] = "Thursday"
    newDayOfWeek[5] = "Fri" // 이런식으로 추가도 됨
    println(newDayOfWeek.toSortedMap())
}
data class Fruit(val name: String, val price: Double)

배열리스트 (ArrayList)

  • 동적 배열을 생성하는것으로, 컬렉션을 일종
  • ArrayList는 동적 배열을 만들기 때문에, 필요에 따라 증가/감소할 수 있다. (특정 크기에 제한되지 않아 좋다)
  • 읽기, 쓰기 모두 가능하며, 삽입 시퀀스 순서를 따른다.
  • 중복 가능하다
fun main() {
    val arr=ArrayList<Double>(5)
    arr.add(1.1)
    arr.add(2.2)
    arr.add(3.3)
    arr.add(4.4)
    arr.add(5.5)
    var sum:Double=0.0
    for(i in arr){
        sum+=i
    }
    println(sum/arr.size)
}

람다식

  • 이름이 없는 함수 (이름이 없는 익명의 함수와는 다름)
  • "->" 를 사용한다
fun main() {
    val sum:(Int,Int) -> Int = {a:Int, b:Int -> a+b}
    println(sum(3,4))
    val ssum={a:Int, b:Int -> println(a+b) }
    ssum(10,5)
}

접근 제한자 - public, private, protected, internal

  • 코틀린에서 클래스, 인터페이스, 프로퍼티를 제한하는데 사용하는 키워드
  • public
    • 프로젝트에 어느 곳에서나 수정 가능
    • 코틀린의 default 제한자이다. (클래스나 인터페이스에 따로 적지 않으면 public임)
  • private
    • 프로퍼티, 필드 등이 선언된 블록에서만 요소에 접근할 수 있다
  • internal
    • 자바에는 없는 코틀린만의 기능
    • internal 제한다는 시행된 모듈 안에서만 필드가 보이게 된다.
    • 모든 필드는 internal로 선언되고 이는 시행된 모듈 안에서만 접근 가능하다.
  • open
    • 코틀린에서 모든 클래스는 자동으로 default라, 기본적으로 상속받을 수 없다.
      • 자바와는 다름. 자바는 모든 클래스가 상속할 수 있기 때문에 default라고 명시해야 한다.
    • 그래서 코틀린은 상속을 사용하려면 클래스를 open으로 만들어야 한다.
  • protected
    • 클래스,인터페이스의 protected 제한자를 붙이면, 그 안의 클래스 또는 서브 클래스에 보이게 해준다.
    • 서브 클래스 안의 오버라이딩한 protected 선언은 따로 수정을 명시하지 않는 이상 보호받는다
    • protected 제한다는 최상위에 선언될 수 없다. => 패키지는 protected 불가능

중첩, 내부 클래스

  • 중첩 클래스 : 다른 클래스 안에 생성된 클래스
    • 코틀린에서는 기본적으로 static이다. => 그 데이터 멤버와 멤버 함수는 클래스 객체를 생성하지 않고도 접근 가능
    • 중첩 클래스는 외부 클래스의 데이터 멤버에 접근할 수 없다. (일방적인 관계임)
  • 내부 클래스 : 키워드 inner를 사용한 다른 클래스 안의 클래스
    • inner라고 표시된 중첩 클래스가 내부 클래스이다. (여전히 중첩인데 inner가 추가된 것뿐)
    • 내부 클래스는 인터페이스 안에, 또는 내부 중첩 클래스가 아닌 곳에 선언될 수 없다.
    • 장점은 private이더라도 외부 클래스 멤버에 접근할 수 있다.
    • 외부 클래스 객체의 참조를 저장한다.

Safe Cast, Unsafe Cast 연산자

  • Unsafe cast 연산자 : as
    • 어떤 때는 변수를 캐스트하지 못하고 예외처리 된다.
  • Safe cast 연산자 : as?
    • 캐스팅할 수 없을 시, 예외처리 대신 null값을 돌려준다.

Try-Catch 문으로 예외 처리하기

  • 키워드 throw에 예외 이름을 사용하면 Throwable class를 사용할 수 있다.
  • 예외처리에서는 try, catch, finally, throw 라는 주요 키워드가 있다.
  • try 블록은 예외를 발생시킬 수 있는 구문 세트를 포함한다.
  • try 뒤에 catch나 finally, 아니면 둘 다 따라와야 한다.
  • catch 블록이 try에서 던진 예외를 잡는다. (예외가 없으면 catch는 실행되지 않는다)
  • final 블록은 예외가 처리되든 말든 실행된다.
  • throw는 오류를 일으키기 위해 입력하는 것으로, 오류가 어디서 나는지 테스트할 때 유용하다.

코틀린 관련 질문 50가지

https://www.ubuntupit.com/frequently-asked-kotlin-interview-questions-and-answers/

반응형

'프로그래밍 강의 > Kotlin' 카테고리의 다른 글

[Kotlin] 코틀린 객체 지향 프로그래밍 기초  (0) 2022.12.28
[Kotlin] 코틀린 기초  (1) 2022.12.28
Comments