코틀린 기초문법2

imssu·2023년 3월 21일
0

Kotlin

목록 보기
2/3
post-thumbnail

컬렉션 타입

Array

  • 배열 표현
  • [ ], set(), get() 이용
fun main() {
	val data: Array<Int> = Array(3, {0})
    					//배열 사이즈, 초기값/[0,0,0]
	data[0] = 10
    data[1] = 20
    data.set(2, 10) //배열에서 2번째 데이터를 30으로 설정
    
    println(array size: ${data.size})
    println(array data: ${data[0]}, ${data.get(1)})
}
  • 기초 타입의 배열

    • 기초 타입이면 BooleanArray, ByteArray, IntArray 등의 클래스 이용 가능
    	val data1: IntArray = IntArray(3, {0})
     	val data2: BooleanArray = BooleanArrya(2, {true})
  • arrayOf() 함수를 이용해 배열 선언과 동시에 값을 할당할 수 있음
    	val data1 = intArrayOf(10, 20, 30)
    	val data2 = booleanArrayOf(true, false)
     val data3 = arrayOf<Int>(1, 2, 3)

List, Set, Map(데이터 집합)

  • List: 순서O, 중복 허용

    • 불변: List, ListOf()
    • 가변: MutableList, mutableListOf()
    	var list1 = listOf<Int>(10, 20, 30)
    	var mutableList1 = mutableListOf<Int>(1, 2, 3)
    	mutableList1.add(3, 4)
    	mutableList1.set(0, 5)
    
    //val 타입의 mutableList라면?
    	val mulist1: MutableList<Int> = mutableListOf(1, 2, 3)
    	var mulist2: MutableList<Int> = mutableListOf(4, 5, 6)
      
      	mulist1 = mutableListOf(9, 8, 7)    //error
      	mulist2 = mutableListOf(0, 1, 2)    //OK
    //val로 선언하면 새로운 mutableList를 못받는다.
  • Set: 순서X, 중복 허용X

    • 불변: Set, setOf()
    • 가변: MutableSet, mutableSetOf()
  • Map: 순서X, 중복 허용X, 키<->값으로 이루어짐

    • 불변: Map, mapOf()
    • 가변: MutableMap, mutableMapOf()
    	var map = mapOf<String, String>(Pair("one", "hello"), "two" to "world")
      	
        println(
        	"""
          map size: ${map.size}
          map data: ${map.get("one"), ${map.get("two")}}
          //hello, world 출력
          """
        )

조건문 if, when

  • 표현식 : 결괏값을 반환하는 계산식
val result = if (data > 0) {
	true // 참이면 result에 true가 들어갑
} else {
	false
}
println(result)

when

  • switch와 같은 기능
  • 표현식으로 사용 가능, -> 다음 넣고 싶은 값 입력
when (data) {
	10 -> println("10")
    20 -> println("20")
    else -> {
    	println("nothing")
    }
}

//조건을 data 타입, 범위로 다양하게 명시
var data: Any = 10
when (data) {
	is String -> println("str")// is는 타입을 확인하는 연산자
    20, 30 -> println("20 or 30")
    in 1..10 -> println("1~10")// in은 범위 지정 연산자
    else -> println("nothing")
}

반복문 for, while

for

  • 범위 연산자 in을 주로 사용
  • for(i in 1..10) -> i가 1씩 1부터 10까지 증가
  • for(i in 1 until 10) -> i가 1부터 9까지 증가(10 미만)
  • for(i in 1.. 10 stpe 2) -> i가 2씩 증가
  • for(i in 10 downTo 1) -> i가 10부터 1까지 감소
  • indices는 컬렉션 타입의 인덱스 값을 의미
	for(i in data.indices) {
    	print(data[i])
        if(i !== data.size -1) print(",")
    }//!==, === -> 객체가 다른가 같은가(주소)
  • withIndex()를 이용하면 인덱스와 실제 데이터를 함께 가져올 수 있음
	for((index, value) in data.withIndex()) {
    	print(value)
        if(index !== data.size -1) print(",")
    }//!==, === -> 객체가 다른가 같은가(주소)

when

  • 종료시점이 정해지지 않았을 때 주로 사용
profile
안녕하세요!

0개의 댓글