HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
Kotlin docs
Kotlin docs
/
▶️
Basic Types
▶️

Basic Types

 

Basic types

  • 이 장에서는 코틀린의 기본 타입
    • numbers, booleans, characters, strings, and arrays. 에 대해서 알아보자
    •  

Numbers

Integer types

코틀린은 네가지 타입의 정수 타입을 가진다.
Type
Size (bits)
Min value
Max value
Byte
8
-128
127
Short
16
-32768
32767
Int
32
-2,147,483,648 (-2^31)
2,147,483,647 (2^31 - 1)
Long
64
-9,223,372,036,854,775,808 (-2^63)
9,223,372,036,854,775,807 (2^63 - 1)
 
초기화 값이 Int 의 최댓값을 넘지 않는 모든 변수는 Int 로 타입 추론된다.
초기화 값이 Int 의 범위 안이라면 Long 으로 타입 추론된다.
Long 을 명시적으로 선언하고 싶다면 숫자 리터럴에 L suffix 를 달면된다.
 
val one = 1 // Int val threeBillion = 3000000000 // Long val oneLong = 1L // Long val oneByte: Byte = 1

Floating-point types

실수 숫자는 Float 과 Double 두 가지 자료형으로 나타냅니다.
Type
Size (bits)
Significant bits
Exponent bits
Decimal digits
Float
32
24
8
6-7
Double
64
53
11
15-16
 
소숫점 (period, .)으로 구분된 숫자를 통해 Double, Float 변수를 초기화 할 수 있습니다.
컴파일러는 기본적으로 Double 타입으로 추론합니다.
 
val pi = 3.14 // Double // val one: Double = 1 // Error: type mismatch val oneDouble = 1.0 // Double
 
명시적으로 Float 타입으로 선언하기 위해서 suffix f 혹은 F 를 실수형 숫자 리터럴에 달아야 합니다.
precision 을 넘어가면 자동으로 rounding 됩니다.
val e = 2.7182818284 // Double val eFloat = 2.7182818284f // Float, actual value is 2.7182817
 
코틀린은 implicit 한 숫자 타입 변환을 지원하지 않습니다.
fun main() { fun printDouble(d: Double) { print(d) } val i = 1 val d = 1.0 val f = 1.0f printDouble(d) // printDouble(i) // Error: Type mismatch // printDouble(f) // Error: Type mismatch }
Explicit conversion을 해야합니다.

 

Literal constants

다양한 정수 리터럴
  • Decimals: 123
    • Longs are tagged by a capital L: 123L
  • Hexadecimals: 0x0F
  • Binaries: 0b00001011
 
실수형 리터럴
  • Doubles by default: 123.5, 123.5e10
  • Floats are tagged by f or F: 123.5f
 
리터럴에 underscore 이용 가능
val oneMillion = 1_000_000 val creditCardNumber = 1234_5678_9012_3456L val socialSecurityNumber = 999_99_9999L val hexBytes = 0xFF_EC_DE_5E val bytes = 0b11010010_01101001_10010100_10010010
 

Numvers representation on the JVM

JVM platform 에서 숫자는 primitive type에 저장됩니다. e.g. (int, double)
Int? 와 같은 nulable number reference 를 사용하거나 generic에서 사용하면 Integer, Double 같은 wrapper class 가 활용됩니다.
 
Java 의 AutoBoxing Unboxing 과 JVM 의 Integer 클래스 메모리 최적화에 따라 nullable 참조에 대해서 직관과 다른 equals 가 동작 할 수 있다.
 
@See Before - 코틀린 동등성 연산
fun main() { val a: Int = 100 val boxedA: Int? = a val anotherBoxedA: Int? = a //-128 ~ 127 사이의 Integer는 는 재활용 val b: Int = 10000 val boxedB: Int? = b val anotherBoxedB: Int? = b println(boxedA === anotherBoxedA) // true println(boxedB === anotherBoxedB) // false }
 

명시적인 형변환 Explicit conversions

All number types support conversions to other types:
  • toByte(): Byte
  • toShort(): Short
  • toInt(): Int
  • toLong(): Long
  • toFloat(): Float
  • toDouble(): Double
  • toChar(): Char
 

Arithmetical Oprations over numbers

+, -, *, /, %
 
코틀린은 custom classes 에 대한 연산자 오버로딩을 지원한다!
 

Bitwise Operations on integer numbers

Int 와 Long 타입만 지원
Here is the complete list of bitwise operations:
  • shl(bits) – signed shift left
  • shr(bits) – signed shift right
  • ushr(bits) – unsigned shift right
  • and(bits) – bitwise and
  • or(bits) – bitwise or
  • xor(bits) – bitwise xor
  • inv() – bitwise inversion
 

실수 자료형 비교

  • Equality checks: a == b and a != b
  • Comparison operators: a < b, a > b, a <= b, a >= b
  • Range instantiation and range checks: a..b, x in a..b, x !in a..b
 
특이한점
  • NaN is considered equal to itself
  • NaN is considered greater than any other element including POSITIVE_INFINITY
  • 0.0 is considered less than 0.0
 

Unsigned 정수형

  • UByte: an unsigned 8-bit integer, ranges from 0 to 255
  • UShort: an unsigned 16-bit integer, ranges from 0 to 65535
  • UInt: an unsigned 32-bit integer, ranges from 0 to 2^32 - 1
  • ULong: an unsigned 64-bit integer, ranges from 0 to 2^64 - 1
 
리터럴에 suffix u 혹은 U를 통해 unsigned 리터럴을 나타넨다.

Boolean

Built-in operations on booleans include:
  • || – disjunction (logical OR)
  • && – conjunction (logical AND)
  • ! - negation (logical NOT)
|| and && work lazily.
 

Characters

  • 문자는 타입 Char 로 표시한다.
  • 문자 리터럴은 single qutes로 표시한다 : `1`
  • 특수 문자들은 backslash 로 escape 한다. \t, \b, \n, \r, \', \", \\ and \$
 

Strings

  • 문자열은 타입 String 으로 표시한다.
  • 문자열 리터럴은 double qutes로 표시한다 : “1123 abcd"
 
  • 문자열은 for-each 구문을 통해 문자에 접근할 수 있다.
for (c in str) { println(c) }
 
  • 문자열은 불변이다.
  • 문자열은 + 연산자로 concatinate 할 수 있다.
    • 대부분의 경우 String template 을 활용하는 것이 더 권장된다.
 
 

String literals

코틀린의 문자열 리터럴에는 두가지 종류가 있다.
  • escaped strings
    • val s = "Hello, world!\n"
  • raw strings
    • val text = """ for (c in "foo") print(c) """
      margin 공백을 제거하기 위해서 trimMargin() 함수를 사용 할 수 있다.
      val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) """.trimMargin()
       
       

String Templates (String Interpolation)

val i = 10 println("i = $i") // prints "i = 10"
val s = "abc" println("$s.length is ${s.length}") // prints "abc.length is 3"
raw string limteral 에서도 사용할 수 있음
val price = """ ${'$'}_9.99 """
 

Arrays

코틀린의 배열은 Array 클래스로 표현된다.
get set 함수는 [] 으로 변환되고 size 함수는 length 로 변환된다.
 
arrayOf() 함수를 사용해 배열을 만들 수 있다.
// Creates an Array<String> with values ["0", "1", "4", "9", "16"] val asc = Array(5) { i -> (i * i).toString() } asc.forEach { println(it) }
 
코틀린의 배열은 invariant 하다.
 
primitive type을 위한 배열 클래스를 제공한다.
val x: IntArray = intArrayOf(1, 2, 3) x[0] = x[1] + x[2]
 
// Array of int of size 5 with values [0, 0, 0, 0, 0] val arr = IntArray(5) // e.g. initialise the values in the array with a constant // Array of int of size 5 with values [42, 42, 42, 42, 42] val arr = IntArray(5) { 42 } // e.g. initialise the values in the array using a lambda // Array of int of size 5 with values [0, 1, 2, 3, 4] (values initialised to their index value) var arr = IntArray(5) { it * 1 }