Kotlin Study 02

박채빈·2021년 9월 15일
0

KotlinStudy

목록 보기
2/7
post-thumbnail

IDE : Intellij
JDK : zulu11

Kotlin 패키지

다른 패키지에 선언된 같은 이름의 클래스는 충돌하지 않습니다.


defaultPackage.kt

fun main(args: Array<String>) {
    val intro: String = "안녕하세요!"
    val num: Int = 20

    println("intro: $intro, num:: $num")
}

String 타입의 intro와 Int 타입의 num을 출력하는 소스
String 키워드를 클릭하고 ctrl+B 를 누르면 아래처럼 String.kt를 열어볼 수 있다.

  • String.kt
/*
 * Copyright 2010-2016 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package kotlin

/**
 * The `String` class represents character strings. All string literals in Kotlin programs, such as `"abc"`, are
 * implemented as instances of this class.
 */
public class String : Comparable<String>, CharSequence {
    companion object {}
    
    /**
     * Returns a string obtained by concatenating this string with the string representation of the given [other] object.
     */
    public operator fun plus(other: Any?): String

    public override val length: Int

    /**
     * Returns the character of this string at the specified [index].
     *
     * If the [index] is out of bounds of this string, throws an [IndexOutOfBoundsException] except in Kotlin/JS
     * where the behavior is unspecified.
     */
    public override fun get(index: Int): Char

    public override fun subSequence(startIndex: Int, endIndex: Int): CharSequence

    public override fun compareTo(other: String): Int
}

defaultPackage.kt (import kotlin.math.*)

import kotlin.math.*

fun main(args: Array<String>) {
    val intro: String = "안녕하세요!"
    val num: Int = 20

    println(PI)
    println(abs(-12.6))

    println("intro: $intro, num:: $num")
}

PI는 기본 패키지에 포함되지 않은 상수이기 때문에, 별도로 패키지를 import 해야 한다.


UserClassImport.kt

import com.example.edu.Person as User

fun main(args: Array<String>) {
    val user1 = User("Kildong", 30)
    val user2 = Person("A123", "Kildong")

    println(user1.name)
    println(user1.age)

    println(user2.name)
    println(user2.id)
}

이름은 같지만 다른 패키지에 존재하는 클래스를 같은 파일에서 사용하는 방법.

import com.example.edu.Person as User

와 같이 선언하여 클래스 별명을 지정하여 충돌을 회피하였다.

Default Package

위 String과 같이 자주 사용하는 클래스와 함수를 미리 만들어 놓은 것.

패키지 이름설명
kotlin.*Any, Int, Double 등의 핵심 함수와 자료형
koltin.text.*문자와 관련된 API
kotlin.sequences.*컬렉션 자료형의 하나로, 반복이 허용되는 객체를 열거
kotlin.ranges.*if문이나 for문에서 사용할 범위 관련 요소
kotlin.io.*입출력 관련 API
kotlin.colections.*List, Set, Map 등의 컬렉션
kotlin.annotation.*애너테이션 관련 API
profile
안드로이드 개발자

0개의 댓글