[Kotlin]변수와 상수 / Variables and Constants

👉🏻 아래는 변수와 상수를 사용해서 화면과 터미널에 값을 출력하는 앱입니다.
Below is an app that uses variables and constants to output values ​​to the screen and terminal.

👉🏻 변수란 어떤 값을 담는 그릇과 같으며 최초에 값이 할당된 후(초기화라고 함) 값의 변경이 가능은 것을 의미합니다.
A variable is like a container that holds a value, and it means that the value can be changed after it is initially assigned a value (called initialization).

👉🏻상수란 어떤 값을 담는 그릇과 같으며 최초에 값이 할당된 후(초기화라고 함) 값을 변경 할 수 없는 것을 의미합니다.
A constant is like a container that holds a value, and after a value is initially assigned to it (called initialization), its value cannot be changed.

👉🏻 변수와 상수 선언
Declare variables and constants

✔️ Kotlin Compose에서 상수는 다음과 같은 형식으로 선언합니다.
In Kotlin Compose, constants are declared in the following format:

— 타입추론이 가능해서 타입을 생략해서 사용할 수 있습니다.
Because type inference is possible, you can omit the type and use it.

val 상수명[constant name] : 타입[Type] = 값[Value]

val 상수명[constant name] = 값[Value]

✔️ Kotlin Compose에서 변수 선언은 다음과 같은 형식으로 선언합니다.
In Kotlin Compose, variable declarations are declared in the following format:

— 타입추론이 가능해서 타입을 생략해서 사용 할 수 있습니다.
Because type inference is possible, you can use it by omitting the type.

var 변수명[variable name] : 타입[Type] = 값[Value]

var 변수명[variable name] = 값[Value]

👉🏻 변수와 상수의 사용방법 예
Examples of how to use variables and constants

// 변수 / Variable
var countVar2 = 10       // 초기화 / Initialization
    countVar2 = 10 + 1   // 값의 변경 가능 / Values ​​can be changed

// 상수 / Constant
val countLet2:Int
    countLet2 = 20       // 초기화 / Initialization
    countLet2 = 20 + 1   // 에러발생 / Error occurred

👉🏻 Compose는 아래와 같은 코드가 에러를 발생시키지 않습니다.
Compose does not throw an error for code like this:

val countVal = countVar + 1 

👉🏻 Compose에서는 LaunchedEffect(Unit) {}는 Swift의 init(){}과 같은 역할을 수행합니다.
In Compose, LaunchedEffect(Unit) {} acts like Swift’s init(){}.

👉🏻 변수와 상수의 출력
Output of variables and constants

✔️터미널 출력 :
terminal output

— 초기화에 대한 문제가 없기 때문에 println으로 출력하면 됩니다.
Since there is no problem with initialization, you can just output it with println.

// 상수나 변수이 값만 출력하는 경우  
// If only the value of a constant or variable is output

println(countVar)
println(countVal)

// 상수나 변수를 문자열과 함께 출력하는 경우
// When printing constants or variables with strings

println("countVar:${countVar}")  // 10
println("countVar2: $countVar2") // 12
println("countVal: $countVal")   // 11
println("countVal2: $countVal2") // 20

✔️뷰에 출력 :
output to view

— 뷰에는 다음과 같은 방식으로 출력 할 수 있습니다.
The view can be output in the following ways:

// 변수와 상수가 문자열과 함께 출력하는 경우
println("countVar:${countVar}") // 변수 / Variable
println("countVal:${countVal}") // 상수 / Constant

// 변수나 상수 값만 출력하는 경우
println(countVar) // 변수 / Variable
println(countVal) // 상수 / Constant

👉🏻 코드 / Code

package com.freelifemakers.variable

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.freelifemakers.variable.ui.theme.VariableTheme


//  변수와 상수 / Variables and Constants
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            VariableTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    ContentView(modifier = Modifier.padding(innerPadding))
                }
            }
        }
    }
}

@Composable
fun ContentView(modifier: Modifier = Modifier) {
    // val :
    // 상수 / constant --> 초기화 후 값을 변경 할 수 없음.
    // constant --> The value cannot be changed after initialization.

    // var :
    // 변수 / variable --> 초기화 후에도 값을 바꿀 수 있음.
    // variable --> The value can be changed even after initialization.

    //  변수 / Variable
    var countVar = 10      // 10
    var countVar2 = 10
        countVar2 = 10 + 2 // 12

    // 상수 / Constant
    val countVal = countVar + 1 // 11
    val countVal2:Int
        countVal2 = 20          // 20
        // countVal2 = 1 --> error

    println("countVar:${countVar}")  // 10
    println("countVar2: $countVar2") // 12
    println("countVal: $countVal")   // 11
    println("countVal2: $countVal2") // 20

   // println("countLet3:${coutLet3}")

    // SwiftUI의 onAppear -> Compose에서는 LaunchedEffect 사용 합니다.
    // 사실 여기서는 사용하지 않아도 기능 구현에 전혀 문제 없습니다.

    // In SwiftUI's onAppear -> Compose, we use LaunchedEffect.
    // In fact, there is no problem implementing the function even if we don't use it here.

    LaunchedEffect(Unit) {
        println("countVal(LaunchedEffect): $countVal")
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {

        Text("Hello, world!")

        // ====        뷰 안에서 변수 출력 방법         ==== //
        // ==== How to output variables in a view ==== //

        Text("Count Var: $countVar")
        Text("Count Var2: $countVar2")
        Text("Count Value: ${countVal}")
        Text("Count Value2: ${countVal2}")
    }
}

@Preview(showBackground = true)
@Composable
fun ContentViewPreview() {
    VariableTheme {
        ContentView()
    }
}

Leave a Reply