简体   繁体   中英

How can I get a variable from one function to another in Kotlin

How can I make a local variable in Kotlin accessible in another function? In python you can use global to make a variable accessible everywhere. What is the equivalent of that in Kotlin?

This is my code:

fun add(){
    val a: Int = 3
    val b: Int = 5
    val c: Int = a + b
}

fun multiply(value: Int){
    println(value * 5)
}

How can I pass variable c as a parameter for the multiply function so that it would run like multiply(c) . From what I've understood, c is a local variable and can only be accessed in the add function. How can I make it a global scope variable?

You have to initialize the variable outside of the function.

var x = 100

fun fn() { 
 x = x + 100 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM