Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply() function in Scala giving a compile error?

Hey I have the following piece of code:

var z:Array[String] = new Array[String](4);
z(0) = "Dave"; 
z(1) = "Joe";
z(2) = "Jim";
z.apply(3) = "Roger";

The last line here is giving a compile time error saying - "missing arguments for method apply in class Array; follow this method with `_' if you want to treat it as a partially applied function"

This does not make sense to me, as I have read that when you apply parentheses surrounding one more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. So if the following line:

z(2) = "Jim";

gets converted to

z.apply(2) = "Jim";

Then why does the line

z.apply(3) = "Roger";

give me a compile time error?

I am new with Scala so any help would be great thanks!

like image 401
fulhamHead Avatar asked Jan 08 '23 10:01

fulhamHead


1 Answers

This call:

z(2) = "Jim";

Gets translated to

z.update(2, "Jim")

apply doesn't work when you try to assign the value.

Update

You can check it by yourself. Run in the console: scala -print, and type val ar = Array(1, 2, 3)

Then, when you type next line ar(2) = 5, it will show you the generated code. It's a bit complicated (the interpreter adds a lot of stuff for it's own purpose), but you will be able to find this (or similar) line:

    $line3.iw.ar().update(2, 5);
like image 111
Archeg Avatar answered Jan 14 '23 18:01

Archeg