Kotlin programozás - Szoftverfejlesztés fórum

üzenetek

hozzászólások


csendes
(őstag)
Blog

Sziasztok, elég kihalt itt, de talán olvassa valaki. Kezdő tanfolyam vizsgafeladatnál akadtam el a függvényeknek történő paraméterátadás rejtélyeinél. A példa egy vizsgafeladatból lett kimazsolázva, önmagában nincs értelme, csak szemléltetésképpen készült. [Kotlin Playground]-on lett futtatva, a vizsga is hasonló környezetben volt. Utólag sikerült az eredeti feladatot másképp megoldani, de nem értem, hogy miért módosulnak az értékként a függvény hívásakor átadott paraméterek. :F
Kód:
/*
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
import java.util.Arrays

fun mySubFunction(entry: Int):Int {
var newentry=entry
newentry+=10
return newentry
}

fun myMainFunction(anyArray: Array<Int>):Int {
val constArray=anyArray
println("This is the original constArray in myMainFunction: ${Arrays.toString(constArray)}")
var newArray=constArray
val n=newArray.count()-1
for (i in 0..n){
newArray[i]=mySubFunction(newArray[i])
}
println("This is the new anyArray in myMainFunction: ${Arrays.toString(anyArray)}") // Why is it modified?
println("This is the new constArray in myMainFunction: ${Arrays.toString(constArray)}") // How can a const Array change?
println("This is newArray in myMainFunction: ${Arrays.toString(newArray)}") // This is OK
var k=1
return k
}

fun main() {
var myArray=arrayOf<Int>(1,2,3,4,5)
var counter: Int
counter=myMainFunction(myArray)
println("This is the new myArray in Main: ${Arrays.toString(myArray)}") // How can this change, the function has only returned an integer?
}

Eredmény/output:
This is the original constArray in myMainFunction: [1, 2, 3, 4, 5]
This is the new anyArray in myMainFunction: [11, 12, 13, 14, 15]
This is the new constArray in myMainFunction: [11, 12, 13, 14, 15]
This is newArray in myMainFunction: [11, 12, 13, 14, 15]
This is the new myArray in Main: [11, 12, 13, 14, 15]

üzenetek