无法在Kotlin中重新为Val分配局部变量的编译时错误 [英] Val cannot be reassigned a compile time error for a local variable in fun in Kotlin

查看:611
本文介绍了无法在Kotlin中重新为Val分配局部变量的编译时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在有趣的交换中,我试图用b1更改a1的值,但它显示无法重新分配val编译时错误" .如果我不能这样改变,那怎么办?

Here in fun swap I am trying to change the value of a1 with b1, but it shows "val cannot be reassigned compile time error". If I can't change like this, then how is it possible to do?

fun swap(a1: String, b1: String) {
   val temp = a1
   a1 = b1
   b1 = temp
}

注意:这只是一个示例,以了解为什么我不能像Java中那样重新分配局部变量.

Note: This is just a sample to know why I am not able to reassign the local variable as we can do in Java.

推荐答案

在Kotlin中,val声明了最终的只读参考,而这正是编译器错误告诉您的内容

In Kotlin val declares final, read only, reference - and that is exactly what compiler error is telling you with

无法重新分配Val

Val cannot be reassigned

一旦将值分配给val,就无法更改.如果您希望能够重新分配它,则必须将其声明为var

Once you assign value to val, it cannot be changed. If you want to be able to reassign it you have to declare it as var

在Kotlin方法中,参数被隐式声明为最终的val,因此您无法像在Java中那样重新分配它们.

In Kotlin method parameters are implicitly declared as final val, so you cannot reassign them just like you could in Java.

但是代码中的核心错误是您试图交换方法参数.由于方法参数是通过值而不是通过引用传递的,因此在Kotlin中无法实现想要实现的目标(就像在Java中一样).即使您在方法调用中重新分配参数,传递给该方法的原始变量也不会改变.

But the core error in your code is that you are trying to swap method parameters. Since method parameters are passed by value and not by reference what you want to achieve is impossible in Kotlin (just as well as it is impossible in Java). Even if you would reassign parameters inside method call original variables passed to the method would not change.

这篇关于无法在Kotlin中重新为Val分配局部变量的编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆