Spring
Basic
Kotlin 문법
코틀린 기초 자료형

Kotlin

Try kotlin Online (opens in a new tab)

Basic Type

코틀린의 타입은 기본적으로 변수의 뒤에 붙는다.

TypeDescription
Float32-bit floating point number
Double64-bit floating point number
Char16-bit Unicode character
Int32-bit signed integer
varMutable variable
valImmutable variable (final)

예제 코드 👇

val a: Float
val b: Double
var c: Char
var d: Int

var and val

  • var : mutable variable
  • val : immutable variable (final)
val popcorn = 5
val hotdog = 7
val total = popcorn + hotdog 
val hamburger = 10
total = total + hamburger // 에러 발생
println(total)

Null Safe

타입 뒤에 ? 붙임

  • 변수?: = null : null 일 때 값 넣어줌
val a: Int? = null
println(a) // null
val b = a?: 0 /// null 이 아닐 때 넣어줌

let - run

기본형은 변수?.let { } ?: run { }와 같이 생겼으며 ?: run { } 부분은 null일 경우 실행된다.

fun main() {
	var i: Int? = null
	
	i?.let {
		println("i is not null : ${i}")
	}?: run {
		println("i is null")
	}
}

String

dart와 동일하다.

val customers = 5
println("There are $customers customers") // There are 5 customers
println("There are ${customers + 1} customers") // There are 6 customers

String with loop

fun main() {
  val str = "abcd"
    for (c in str) {
        println(c)
    }
}

uppercase()

+

val str = "Hello "
val str2 = "World"
println(str + str2) // Hello World

Collection

List, Sets, Maps 등의 컬렉션을 제공한다.

List

MutableListmutableListOf() (opens in a new tab), ListlistOf() (opens in a new tab)가 있다.

final로 선언한 리스트와는 달리 값을 아예 변경할 수 없는 완전한 불변 리스트를 만들 수 있다.

  • 값 추가 : .add()
  • 값 삭제 : .remove()
  • range : a..<b (b는 포함 되지 않음)
  • in 키워드 사용가능
fun main() {
  val readOnlyShapes = listOf("triangle", "square", "circle")
	println(readOnlyShapes[0..2]) // [triangle, square]
	readOnlyShapes[0] = "value change" // 에러 발생
  println(readOnlyShapes) 
}
val shapes: MutableList<String> = mutableListOf("triangle", "square", "circle")
val shapesLocked: List<String> = shapes
2차원 List

코틀린에서는 [][]이런식으로 사용하지 않고 하나의 중괄호 안에 ,를 이용해서 row column을 구분한다.

fun main() {
    val array = listOf(
        listOf(1, 2, 3),
        listOf(4, 5, 6),
        listOf(7, 8, 9)
    )
    val value = array[1][2]
    println(value) // 6
}
indexed operator
a[i_1, ]
.count()

Set()

  • immutable :
    • Type : Set()
    • 선언 : a: Set() = setOf()
  • mutable :
    • Type : MutableSet()
    • 선언 : a: MutableSet() = mutableSetOf()
val readOnlyFruit = setOf("apple", "banana", "cherry", "cherry")
val fruit: MutableSet<String> = mutableSetOf("apple", "banana", "cherry", "cherry")
 
println(readOnlyFruit) // [apple, banana, cherry]
add() remove()
val fruit: MutableSet<String> = mutableSetOf("apple", "banana", "cherry", "cherry")
fruit.add("dragonfruit")    // Add "dragonfruit" to the set
println(fruit)              // [apple, banana, cherry, dragonfruit]
 
fruit.remove("dragonfruit") // Remove "dragonfruit" from the set
println(fruit)      

Map

  • immutable :
    • Type : Map<T,R>
    • 선언 : a: Map<String, Int>() = mapOf("apple" to 100)
  • mutable :
    • Type : MutableMap<T,R>
    • 선언 : a: MutableMap<String, Int> = mutableMapOf("apple" to 100)
put() and remove()
fun main() {
    val juiceMenu: MutableMap<String, Int> = mutableMapOf("apple" to 100, "kiwi" to 190, "orange" to 100)
    juiceMenu.put("dragon fruit", 200)
    println(juiceMenu) // {apple=100, kiwi=190, orange=100, dragon fruit=200}
    juiceMenu.remove("apple")
    println(juiceMenu) // {kiwi=190, orange=100, dragon fruit=200}
}
containsKey()

containsValue()도 있다.

fun main() {
    val juiceMenu: MutableMap<String, Int> = mutableMapOf("apple" to 100, "kiwi" to 190, "orange" to 100)
    println(juiceMenu.containsKey("apple")) /// true
}
keys, values
fun main() {
    val juiceMenu: MutableMap<String, Int> = mutableMapOf("apple" to 100, "kiwi" to 190, "orange" to 100)
    print(juiceMenu.keys)
    print(juiceMenu.values)
}