들어가며

이번 글에서는 처음으로 코틀린을 공부해보는 만큼 코틀린에 쓰이는 기본타입(numbers, characters, booleans, arrays, and strings)에 대해서 알아보도록 하겠습니다. 

 

1. Numbers

1. 정수

1. 파이썬, javascript처럼 변수에 따로 타입을 선언하지 않음

2. 일반적인 정수를 저장하면 Int로 설정

3. Int의 범위 밖이나 뒤에 L을 추가하면 Long으로 설정

4. 변수이름 : 타입 = ? 구문을 통해서 직접 타입 설정 가능 

val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1

2. 실수

val pi = 3.14 // Double
val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float, actual value is 2.7182817

1. 일반 실수 입력시 Double로 설정

2. 뒤에 F또는 f 추가시 float으로 설정되고 범위 밖의 데이터는 소멸

3. 독립성

코틀린은 일반적인 언어처럼 숫자 파라미터가 포괄적인게 아니라 해당 파라미터만 수용가능, 그렇지 않을 경우 에러 발생

fun main() {
    fun printDouble(d: Double) { print(d) }

    val i = 1    
    val d = 1.1
    val f = 1.1f 

    printDouble(d)
//    printDouble(i) // Error: Type mismatch
//    printDouble(f) // Error: Type mismatch
}

4.. 리터럴 상수(Literal constants)

  • 10진수, Decimals: 123
    • Longs are tagged by a capital L: 123L
  • 8진수,  Hexadecimals: 0x0F
  • 2진수, Binaries: 0b00001011

NOTE: Octal literals are not supported.

 

  • Doubles by default: 123.5, 123.5e10
  • Floats are tagged by f or F: 123.5f

5. 가독성을 위한  언더스코어 사용가능

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

6. 변환

val b: Byte = 1 // OK, literals are checked statically
val i: Int = b // ERROR

타입은 명백히 독립적이므로 바로 대입하는것은 불가(java와 다름)

변환하기 위해선 toInt,toLong등의 메서드 사용필요

val i: Int = b.toInt() // OK: explicitly widened
print(i)
  • toByte(): Byte
  • toShort(): Short
  • toInt(): Int
  • toLong(): Long
  • toFloat(): Float
  • toDouble(): Double
  • toChar(): Char

*오퍼레이터 오버로딩

val l = 1L + 3 // Long + Int => Long

서로 다른 두 데이터의 수학적 계산 결과의 타입은 자동으로 최적화됨

 

*나눗셈으로 인한 타입 결정은 java와 같음

7.비교(Floating point numbers comparison)

The operations on floating point numbers discussed in this section are:

  • 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

2.Characters

Characters are represented by the type Char. They can not be treated directly as number

fun check(c: Char) {
    if (c == 1) { // ERROR: incompatible types
        // ...
    }
}

특수문자사용 : \t, \b, \n, \r, \', \", \\ and \$

유니코드 인코딩 : '\uFF00'

 

Convert a character to an Int number

fun decimalDigitValue(c: Char): Int {
    if (c !in '0'..'9')
        throw IllegalArgumentException("Out of range")
    return c.toInt() - '0'.toInt() // Explicit conversions to numbers
}

 

3.Booleans

The type Boolean represents booleans, and has two values: true and false.

Built-in operations on booleans include

  • || – lazy disjunction
  • && – lazy conjunction
  • ! - negation

4.Arrays

Arrays in Kotlin are represented by the Array class

메서드 : set,get( that turn into[] by operator overloading conventions )

특성 : size

 

사용법

1. arrayOf(1, 2, 3) creates an array [1, 2, 3]

2. arrayOfNulls() library function can be used to create an array of a given size filled with null elements.

3. Array constructor

it takes array size and the function that can return the initial value of each array element given its index

// Creates an Array<String> with values ["0", "1", "4", "9", "16"]
val asc = Array(5) { i -> (i * i).toString() }
asc.forEach { println(it) }

Primitive type arrays

ByteArray, ShortArray, IntArray등 Kotlin에는 특수한 배열들이 있습니다. 각 배열은 Array에 상속되지 않지만 동일한 메서드를 사용하며 []를 통해 접근이 가능합니다.

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 }

5.Strings

Strings are represented by the type String

특성

1.Strings are immutable

2.Elements of a string are characters that can be accessed by the indexing operation: s[i]

3. string can be iterated over with a for-loop:

for (c in str) {
    println(c)
}

4.  concatenate strings using the + operator, as long as the first element in the expression is a string

val s = "abc" + 1
println(s + "def")

String literals

1.특수 문자사용

val s = "Hello, world!\n"

2. """ 사용

val text = """
    for (c in "foo")
        print(c)
"""

String templates

$기호를 사용해서 템플릿으로 사용할 수 있음

val i = 10
println("i = $i") // prints "i = 10"

 

중괄호를 사용해서 임의의 표현까지 템플릿으로 사용 가능

val s = "abc"
println("$s.length is ${s.length}") // prints "abc.length is 3"

 

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

Calling Extension  (0) 2021.08.19
[Kotlin] Extension Function  (1) 2021.07.19
Kotlin - 2. Packages and Imports  (0) 2020.03.29

+ Recent posts