Kotlin에서 스코프(scope)는 변수, 함수, 객체 등이 접근 가능한 영역을 정의하는 개념입니다. 코틀린의 스코프는 블록(block), 클래스, 패키지, 그리고 파일 단위로 나뉘며, 이 스코프는 프로그램의 구조와 가독성, 유지보수성을 크게 향상시킵니다.


1. 스코프의 종류

(1) 지역 스코프 (Local Scope)

  • 변수나 함수가 특정 블록 {} 내에서만 접근 가능.
  • 일반적으로 if, for, while, 또는 함수 내에서 사용.

(2) 클래스 스코프 (Class Scope)

  • 클래스 내부에서 정의된 변수와 메서드는 해당 클래스의 스코프 안에서 접근 가능.
  • 클래스 내의 변수는 기본적으로 인스턴스 변수(멤버 변수)로 관리.

(3) 파일 스코프 (File Scope)

  • 파일에 정의된 함수나 변수는 파일 내부에서만 접근 가능.
  • 다른 파일에서 접근하려면 public, internal, private 접근자를 사용.

(4) 패키지 스코프 (Package Scope)

  • 패키지 내에 정의된 함수, 클래스, 객체 등이 패키지 내부에서 접근 가능.
  • 코틀린은 기본적으로 패키지 스코프를 제공하며, Java처럼 명시적으로 package를 선언하지 않아도 됨.

 

2. 스코프별 예시

(1) 지역 스코프

fun localScopeExample() {
    val outerVariable = "I'm accessible throughout this function"

    if (true) {
        val innerVariable = "I'm only accessible inside this if block"
        println(innerVariable) // 접근 가능
    }

    // println(innerVariable) // 오류: innerVariable은 if 블록 외부에서 접근 불가
    println(outerVariable) // 접근 가능
}

 

(2) 클래스 스코프

class Person(val name: String) {
    private val age: Int = 30 // 클래스 내부에서만 접근 가능

    fun displayInfo() {
        println("Name: $name, Age: $age") // 접근 가능
    }
}

fun classScopeExample() {
    val person = Person("John")
    person.displayInfo() // 가능
    // println(person.age) // 오류: age는 private 스코프
}

 

(3) 파일 스코프

private val fileVariable = "I'm only accessible in this file"

fun publicFunction() {
    println("I'm accessible from other files if imported")
}

private fun privateFunction() {
    println("I'm only accessible in this file")
}

 

다른 파일에서

import com.example.Utils.publicFunction

fun fileScopeExample() {
    publicFunction() // 가능
    // privateFunction() // 오류: privateFunction은 접근 불가
    // println(fileVariable) // 오류: fileVariable은 접근 불가
}

 

(4) 패키지 스코프

package com.example

fun packageScopedFunction() {
    println("I'm accessible within this package")
}

다른 패키지에서:

import com.example.packageScopedFunction

fun main() {
    packageScopedFunction() // 가능 (default: public)
}

3. Kotlin 스코프 함수

코틀린에는 **스코프 함수(scope functions)**라고 하는 특수한 함수도 있습니다. 이 함수들은 람다 블록 내에서 객체를 다룰 수 있는 간결한 방법을 제공합니다.

스코프 함수 종류

  • let
  • run
  • with
  • apply
  • also

 

kotlin 스코프 함수에 대해서는 다음번 글에 상세히 알아아보도롭 하겠습니다.

+ Recent posts