简体   繁体   English

如何从一个 function 获取变量到 Kotlin 中的另一个

[英]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.

相关问题 如何从Kotlin中的另一个类获取变量? - How to get a variable from another class in kotlin? Kotlin 从一个类到另一个类获取变量/值 - Kotlin get a variable/value from one class to another 将块从一个 class 传递到另一个时,如何访问 Kotlin 中的私有成员 - How can I access private members in Kotlin when passing a block from one class to another 如何从Java中的另一个类获取变量? - How can I get a variable from another class in Java? 如何从listview获取变量并传递给另一个活动? - How can i get variable from listview and pass to another activity? 如何将功能从另一个类继承到Kotlin中的活动中? - How do I inherit a function from another class into an activity in kotlin? 如何在 onCreateView 中从另一个 function 获取数据? - How can I get data from another function in onCreateView? 如何在 Kotlin 中从一个片段切换到另一个片段? - How can I switch from a fragment to another fragment in Kotlin? 如何从 Kotlin 中的另一个 class 访问 arrayList 项目 - How can I access an arrayList item from another class in Kotlin 如何从另一个活动中获取活动中的变量并在从那里初始化后使主要活动使用变量?(kotlin) - how to get a variable in an activity from another activity and make the main activity to use variable after initializing from there ?(kotlin )
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM