Programming/Kotlin

Kotlin의 기초

코딩하는 포메라니안 2026. 3. 28. 16:24

코틀린이란?

코틀린의 설계 목적

- "간결성"보다는 "가독성"을 높이는 데 목표를 두고 설계된 프로그래밍 언어

- 코틀린에 숙련된 개발자만을 위한 코드는 좋은 코드가 아니며, 수정 및 디버깅도 쉬워야 함

코틀린의 컴파일러

*.kt -> Kotlin compiler -> *.class -> *.jar -> Application(with Kotlin runtime)

 

- JVM에서 실행될 수 있는 바이트 코드가 포함된 클래스 파일을 생성한다.

- 코틀린 컴파일러에 의해 컴파일되기 때문에, 자바를 사용할 때와 다른 부분이 존재한다.

   ex) 자바에서는 체크/언체크 예외를 구분하나, 코틀린에서는 모든 예외를 언체크 예외로 인식한다.

 

코틀린 기초 문법

1. 변수 선언

  • val : 불변 변수
  • var: 가변 변수
  • 변경 가능성보다 불변성을 선호하며, 기본적으로 모든 것이 불변
val brand: String = "BBQ"
var count: Int = 2
count = 3

 

2. 함수 선언

fun add(a: Int, b: Int): Int{
	return a + b
}

//매개변수에 Default값 지정 가능
fun addPerson(name: String "홍길동", age: Int 10): Person{
	return Person(name, age)
}

//단일 표현식 함수
fun multiply(a: Int, b: Int) = a * b

//프로그램 시작하는 main 함수
fun main() {
	val result = add(7, 5) //add(a = 7, b = 5)
	println("Result: $result")
}

 

3. 조건문

  • if-else문
    • if문이 식으로 동작해서, 값을 바로 반환할 수 있다.
fun maxOf(a: Int, b:Int): Int{
	return if (a > b) a else b
}

//자바는 if(a > b) return a; else return b;
  • when문(switch와 유사)
    • 마찬가지로 식으로 동작
fun getGrade(score: Int): String{
	return when (score) {
		in 90..100 -> "A"
		in 80..89 -> "B"
		else -> "F"
	}
}

+) try-catch도 식으로 동작

 

4. 클래스와 객체

  • 생성자를 선언하면서 field 선언을 할 수 있다.
  • 객체 생성 시, new 생략 가능
  • class맴버 변수 접근하듯이 사용하면, getter, setter를 호출해준다.
class Store(val brand: String, var count: Int){//소괄호를 통해 field선언도 하고, 생성자도 생김
	fun summary(){
		println("Brand is $name and count is $count.")
	}
}

fun main(){
	val store = Store("BBQ", 21)
	store.brand //getBrand()으로 호출해줌
	store.summary()
}

//데이터 클래스: 데이터 보관용 DTO 클래스 
//=> toString(), equals(), hashCode(), copy() 메서드를 자동으로 생성해주는 클래스
data class User(val id: Int, val name: String)

 

5. Null Safety

//1. Nullable ?, Non-Nullable 선언: 기본적으로 non-nullable
val nullableName: String? = null //이건 함수 body가 return null임
val nonNullableName: String

//2. Safe call operator ?.
// = null이 아닐 경우에 수행해라 (*Optional의 ifPresent역할)
fun main(){
	personRepository.findId(1L)
		?.updateAge(23)
}

//3. Elvis operator ?:
// = null일 경우 이렇게 대체해라(기본값을 사용하던 예외를 던지던 등등)
fun main(){
	val person: Person = (
		personRepository.findId(1L)
		?: throw NotFoundException("Person Not Found"))
		
	val length = person.name?.length ?: 0
}

 

6. 컬렉션

  • 읽기 전용 collection 타입 & 수정 가능한 collection타입이 분리되어있음
  • 읽기 전용: listOf(), setOf(), mapOf()를 통해 생성 가능하며, add() 등 수정 기능의 함수를 제공하지 않음
  • 수정 가능: mutableListOf(), mutableSetOf(), mutableMapOf()
val stores: List<Store> = listOf(Store("BBQ", 3), Store(), Store())
val storeSet: Set<Store> = setOf(Store("BBQ", 1), Store(), Store())
val map: Map<Category, Store> = mapOf(Category(1, "food") to Store("BBQ", 1))

val mutableStores: MutableList<Store> = mutableListOf(Store("BBQ", 1), Store(), Store())

mutableStores.add(Store())

//.get() 대신 []대괄호로 값 조회 가능
val store = stores[0]
val store = map[Category(1, "food")]

 

7. 확장 함수

  •  기존 클래스에 새로운 함수를 추가할 수 있음
fun String.addPrefix(prefix: String): String{
	return "$prefix$this"
}

fun <T> List<T>.findAnyElement(): T? {
	return this.stream()
		.findAny()
		.orElse(null)
}

fun main(){
	val brand = "BBQ"
	brand.addPrefix("ko_")
}

 

8. 함수를 값처럼 사용

  • webflux에서 operator에 함수를 넣듯이!
  • 함수를 일급객체로 취급
//case1) function body가 존재하는 lambda
val eqBrand = fun(store: Store): Boolean{
	return store.brand == "BBQ"
}

//case2) function body 생략한 lambda
val eqBrand2 = fun(store: Store) = store.brand == "BBQ"

//case3) 중괄호로 감싸진 lambda
val eqTitle3 = { store: Store -> store.brand == "BBQ"}

val stores = listOf(Store("BBQ", 1), Store(), Store())
filterStore(stores, eqBrand)

fun filterBrand(stores: List<Store>, filter: (Store) -> Boolean): List<Store>{
	return stores.filter(filter)
		.toList()
}

'Programming > Kotlin' 카테고리의 다른 글

[Kotlin] 이펙티브 코틀린  (0) 2026.03.31
[Kotlin] 코루틴 (+Virtual Thread)  (0) 2026.03.28