I'm new in scala language I have a listbuffer :
var oldQuestions: Seq[Question] = section.questions
var newQuestions: ListBuffer[Question] = new ListBuffer()
So all I need is,to loop over the newQuestions list and access to one question based on her id and delete it.
Any help would be very appreciated.
Don't use vars, and mutable collections. It is a really, really rare occurrence that you actually need either of those in scala. So, for now, until you get sufficient grip on the language to be able to tell when those rare cases happen, just pretend these things don't exist. Learn to write good functional code before you explore mutability.
To answer your question:
val newQuestions: Seq[Question] = section.questions.filterNot(_.id == idToDelete)
Related
Preamble: I'm teaching a course in object-functional programming using Scala and one of the things we do is to take sample problems and compare how they might be implemented using object-functional programming and using state-based, object-oriented programming, which is the background most of the students have.
So I want to implement a simple class in Scala that has a private var with a public accessor method (a very common idiom in state-based, object-oriented programming). Looking at Alvin Alexander's "Scala Cookbook" the recommended code to do this is pretty ghastly:
class Person(private var _age: Int):
def incrAge() = _age += 1
def age = _age
I say "ghastly" because I'm having to invent two names that essentially represent the age field, one used in the constructor and another used in the class interface. I'm curious if people more familiar with Scala would know of a simpler syntax that would avoid this?
EDIT: It seems clear to me now that Scala combines the val/var declaration with the given visibility (public/private), so for a var either both accessor&mutator are public or both are private. Depending on perspective, you might find this inflexible, or feel it rightly punishes you for using var 🙂.
Yes, a better way of doing it is not using var
class Person(val age: Int) {
def incrAge = new Person(age+1)
}
If you are going to write idiomatic scala code, you should start with pretending that certain parts of it simply do not exist: mostly vars, nulls and returns, but also mutable structures or collections, arrays, and certain methods like .get on a Try or an Option, or the Await object. Oh, and also isInstanceOf and asInstance.
You may ask "why do these things exist if they are not supposed to be used?". Well, because sometimes, in a very few very specific cases they are actually useful for achieving a very limited very specific purpose. But that would be probably fewer than 0.1% of the cases you will come across in your career, unless you are involved in some hard core low level library development (in which case, you would not be posting questions like this here).
So, until you acquire enough command of the language to be able to definitively distinguish those 0.1% of the cases from the other 99.9%, you are much better off simply ignoring those language features, and pretending they do not exist (if you can't figure out how to achieve a certain task without using one of those, post a question here, and people will gladly help you).
You said "Having to create two names to manage a single field is ugly." Indeed. But you know what's uglier? Using vars.
(Btw, the way you typically do this in java is getAge and setAge – still two names. The ugliness is rooted in allowing the value labeled with the given name to be different at different points of program execution, not in how specifically the semantics of mutation looks like).
I have heard that it is a good practice in Scala to eliminate for loops and do things "the Scala way". I even found a Scala style checker at http://www.scalastyle.org. Are for loops a no-no in Scala? In a course at https://www.udemy.com/course/apache-spark-with-scala-hands-on-with-big-data/learn/lecture/5363798#overview I found this example, which makes me thing that for looks are okay to use, but using the Scala format and syntax of course, in a single line and not like the traditional Java for looks in multiple lines of code. See this example I found from that Udemy course:
val shipList = List("Enterprise", "Defiant", "Voyager", "Deep Space Nine")
for (ship <- shipList) {println(ship)}
That for loop prints this result, as expected:
Enterprise Defiant Voyager Deep Space Nine
I was wondering if using for as in the example above is acceptable Scala style code, or it if is a no-no and why. Thank you!
There is no problem in this for loop, but you can use functions form List object for your work in more functional way.
e.g. instead of using
val shipList = List("Enterprise", "Defiant", "Voyager", "Deep Space Nine")
for (ship <- shipList) {println(ship)}
You can use
val shipList = List("Enterprise", "Defiant", "Voyager", "Deep Space Nine")
shipList.foreach(element => println(element) )
or
shipList.foreach(println)
You can use for loops in Scala, there is no problem with that. But the difference is that this for-loop is not an expression and does not return a value, so you need to use a variable in order to return any value. Scala gives preference to work with immutable types.
In your example you print messages in the console, you need to perform a "side effect" to extract the value breaking the referencial transparency, I mean, you depend on the IO operation to extract a value, or you have mutate a variable which is in the scope which maybe is being accessed by another thread or another concurrent task thereby there is no guarantee that the value that you collect wont be what you are expecting. Obviously, all these hypothesis are related to concurrent/parallel programming and there is where Scala and the immutable style help.
To show the elements of a collection you can use a for loop, but if you want to count the total number of chars in Scala you do that using a expression like:
val chars = shipList.foldLeft(0)((a, b) => a + b.length)
To sum up, most of the times the Scala code that you will read uses immutable style of programming although not always because Scala supports the other way of coding too, but it is weird to find something using a classic Java OOP style, mutating object instances and using getters and setters.
Ideally, a common interface or type would allow code compiled to both JS and JVM to make use of a fast Array type without the need to use a buffer. Presumably the fastest array type in Scala.js is a js.Array (resizable) and on the JVM it is the Array (not resizable), so Array does not really work here.
It could be that type classes are the way to go here, but that may be overkill. Still, if it is the best solution, I'd be interested to know.
Another possible solution that comes to mind, that would require a fair bit of collaboration though maybe not a lot of effort, would be to get the new Scala Collections API to agree on an API for just this purpose (although it would not be limited to libraries used on the JS and JVM). It could possibly end up being a restricted view of an existing Array implementation in Scala collections for the JVM, assuming no performance penalties would be incurred with such an approach.
As #sjrd already pointed out, if you are just concerned about the interfaces, all the normal Scala collection interfaces work.
If you are concerned about efficiency, it is worth noting, that in Scala.js, we back a scala.Array by a js.Array (plus some RTTI). So if you use an scm.ArrayBuilder it will essentially boil down to a simple JS Array:
import scala.collection.mutable.ArrayBuilder
val builder = ArrayBuilder.make[Int]
builder += 1
builder += 2
builder += 3
println(builder.result())
Will, after optimization, give you (Scala.js 0.6.19, Scala 2.11.11)
var elems$2 = null;
elems$2 = [];
elems$2.push(1);
elems$2.push(2);
elems$2.push(3);
// builder.result()
var x = $makeNativeArrayWrapper($d_I.getArrayOf(), elems$2);
// println(...)
var this$6 = $m_s_Console$();
var this$7 = $as_Ljava_io_PrintStream(this$6.outVar$2.v$1);
this$7.java$lang$JSConsoleBasedPrintStream$$printString__T__V((x + "\n"))
So, I am new to functional programming and I am still trying to digest the fundamental principles. So far, I can appreciate that one should ideally code without mutable variables, assignments, loops and other imperative control structures. So I have a question. Between the following two code snipets:
def enrich(xRDD: RDD[xObject], yRDD: RDD[yObject], zRDD: RDD[zObject]): RDD[Result] = {
val temp = functionA(xRDD, yRDD)
functionB(temp, zRDD)
}
and
def enrich(xRDD: RDD[xObject], yRDD: RDD[yObject], zRDD: RDD[zObject]): RDD[Result] = {
functionB(functionA(xRDD, yRDD), zRDD)
}
which one should I opt for and why? My guess is the second one since it avoids assigning data locally to a temporary val. Is this all there is to it? Did I get it right? Am I missing something?
Both ways are good but depends on usecase which one to go for.
There is nothing wrong about both the ways. You can use any one of the above ways. But as you are not using the value returned by functionA any where except in functionB. Second way looks good (there is no extra variable). Extra variable is less of a concern (memory consumed by reference is insignificant for practical purposes.)
Misconception
Assignments are OK in functional programming. Reassignments are not OK.
Capturing the result using a variable is OK in functional programming. But using var and reassigning the var is not functional programming.
If you are ok with a bit of reading.
https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-20.html
You will need to dig a bit around compilers theory to see benefits and disadvantages which cause variables.
I know that Scala has var (for mutable state) but pure functional programming discourages use of any mutable state and rather focuses on using val for everything.
Coming from an imperative world it's hard to let go of mutable state.
My question is when is it okay to use var in your Scala code ? Can all code really be done using just val. If yes, then why does Scala have vars?
Here are some reasons for vars in Scala:
Scala is a multi-paradigm language, it encourages functional programming, but it leaves the choice to the programmer.
Comptibility: Many Java APIs expose mutable variables.
Performance: Sometimes using a var gives you the best possible performance.
When people say that everything can be done without vars, that is correct in the sense that Scala would still be turing complete without vars. However, it doesn't change anything about the validity of the previous points.
Even from a functional programming point of view, you can use vars (or mutable objects) locally, if they don't leave the scope where they are defined.
For instance, consider this (contrived) function, which returns the size of a list:
def dumbSize( lst: List[Int] ): Int = {
var i = 0
var rest = lst
while( rest != Nil ) {
i += 1
rest = rest.tail
}
i
}
Although this (ugly) function uses vars, it is still pure. There are no side effects and it will always return the same result for a given argument value.
Another example of "mutable-state-encapsulation" is the actor model, where actor state is often mutable.