[英]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?如何使 Kotlin 中的局部变量可在另一个 function 中访问? In python you can use
global
to make a variable accessible everywhere.在 python 中,您可以使用
global
使变量随处可访问。 What is the equivalent of that in Kotlin? 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)
.我如何传递变量
c
作为multiply
function 的参数,以便它像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?据我了解,
c
是一个局部变量,只能在add
function 中访问。如何使其成为全局变量 scope?
You have to initialize the variable outside of the function.您必须在 function 之外初始化变量。
var x = 100
fun fn() {
x = x + 100
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.