0

I apologize for how basic this question is, however in any case this is my first scala project all i am attempting to do is pass an array into a function and return the function. here's what i have:

 def main(args: Array[String]): Unit = {
    // 9999 == infinite there should be no reason
    // that for the scope of this assignment there
    // there should be a value any bigger than this.
    var Nodes = 4;
    var infi = 9999;
    var pathTaken = Array(Nodes);
    var pathLens = Array(Nodes);
    var paths = Array(Nodes, Nodes);
    
    pathLens = lenInit(pathLens);
}

def pathLens(x : Array[4]): Unit = {
    x = (0, 0, 0, 0);
    return x;
} 

I get that this is super basic and simple but i have been a C/python guy all my life and I have been scavenging the internet up to this point fruitlessly. please help/point me in the right direction many thanks!

itsMe
  • 51
  • 7
  • One point first: you seem to specify `Unit` as return type. You should either leave the compiler find out (so remove the `: Unit` part) or set the correct type you expect. – mfirry May 06 '21 at 10:28

2 Answers2

5

The best thing you can do is to stop and try to learn some basic scala syntax before trying exercises. Can I suggest you a couple great resources to learn Scala?

Book:

Video Tutorials:

Interactive Tutorials:

The answer is OOT but I think it was worth signaling these resources in this case.

Tonio Gela
  • 85
  • 8
2

Assume your intention is that the function is called lenInit and not pathLens?

Anyway, to create an array of 4 integers all set to 0 use Array.fill:

Array.fill[Int](4)(0)

You don't really need an init function, and the type can be inferred so just do this:

val pathLens = Array.fill(Nodes)(0)

See this answer for more Array initializing in Scala

To pass arrays to functions, you need to parameterize the type of array eg:

def foo(x: Array[Int]) .........
mikelegg
  • 1,197
  • 6
  • 10
  • That is a fair point however i will still need to use functions for my arrays further in this assignment could you help me out on how to pass the arrays around? – itsMe May 06 '21 at 10:32
  • how can i use the .fill command on a existing array? I see that you used it when initializing an array but how can i use it to reset an array back to zero? – itsMe May 06 '21 at 10:44
  • @itsMe re. "how to reset an array back to zero": don't. Just create a new one. In scala you should really really rarely if _ever at all_ need to mutate existing structures. While arrays, being an atavism inherited from java are actually mutable, you'll be better off pretending they are not. Just get used to using immutable structures. That is the "scala way". Also, I second the advice given to you by Tonio Gela in the other answer: it seems like it is way too early for you to be writing code. You should start with learning some basic syntax first. – Dima May 06 '21 at 13:23