据我所知,Java是从this post开始按值传递的.我来自Java背景,我想知道Kotlin使用什么来传递其间的值.比如ExtensionsMethods等等.

推荐答案

It uses the same principles like Java. It is always pass-by-value, you can imagine that a copy is passed. For primitive types, e.g. Int this is obvious, the value of such an argument will be passed into a function and the outer variable will not be modified. Please note that parameters in Kotlin cannot be reassigned since they act like vals:

fun takeInt(a: Int) {
    a = 5
}

This code will not compile because a cannot be reassigned.

For objects it's a bit more difficult but it's also call-by-value. If you call a function with an object, a copy of its reference is passed into that function:

data class SomeObj(var x: Int = 0)

fun takeObject(o: SomeObj) {
    o.x = 1
}

fun main(args: Array<String>) {
    val obj = SomeObj()
    takeObject(obj)
    println("obj after call: $obj") // SomeObj(x=1)
}

You can use a reference passed into a function to change the actual object.

Kotlin相关问答推荐

用浮点数或十进制数给出错误答案的阶乘计算

Kotlin-删除按钮周围的空格

如何修改muableStateMapOf的值?

同时也是一个字符串的 Kotlin 枚举

TzdbZoneRulesProvider 在 java.time 中不工作

使用 Jetpack Compose 使用参数导航

如何获取@JsonProperty 名称列表?

如何规避 Kotlin 的泛型类型差异约束

循环中的每个元素都应填充行中可用的所有可用空间

如何在 kotlin 中创建自定义迭代器并添加到现有类?

如何在 Kotlin 中不受约束?

Kotlin - 创建指定长度的随机整数的 ArrayList?

基类中的 ViewModelProviders.get(...)

Kotlin 的 isNullOrBlank() 函数是否可以导入 xml 以用于数据绑定

将 Android Studio 升级到 3.1.0 后的 Android Support 插件错误

项目未与 Gradle 链接

如果作为 RxJava Observable 提供,Kotlin 密封类子类需要强制转换为基类

这是 Kotlin 中的错误还是我遗漏了什么?

如何在 firebase 数据库中使用 kotlin 协程

Kotlin - 如何获取注释属性值