How to start on scala [closed] - scala

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am .NET developer and I'd like to broaden my horizons a bit and after checking out modern tendencies decided to try Scala. Can you please advise a good strategy to start on it? Should I learn Java first? What source or handbook should I read? Is there any OS projects to practice Scala and grow on them?
Thanks,
Dominique

You might gain a first impression by visiting Simply Scala where you have an online interpreter available.
An absolute classic is Scala for Java Refugees which was originally written for people coming from Java, but will be quite helpful for you, considering how similar the basics of C#/Java are.
You don't need to learn Java first , but you need to have the Java runtime/development kit installed and working.
Then go to http://www.scala-lang.org/downloads and download the appropriate package for your operating system (I always prefer the nightly builds of Scala, they have more bug-fixes than the latest stable one).
After that, run the Scala REPL which is basically "Simply Scala offline" (Simply Scala uses the Scala REPL behind the covers, too). Even many Java programmers use the Scala REPL to prototype things first.
If you prefer books to learn I can recommend Programming in Scala (2nd edition) by Martin Odersky (if you start from a language design point of view and want the "reference book"). There are others like "Programming Scala" which are more targeted at beginners so to speak, but personally I found "Programming in Scala" excellent and have learned Scala with just that book.
A nice way to start Scala is working with the collection classes. .NET has added something similar lately with LINQ and extension methods, so it will be easy to pick up for you.
A small example to get you started:
//Define a class with some properties
case class Person(name: String, var age: Int, spokenLanguages: String*)
//Create some persons
val joe = Person("Joe", 42, "English","French","Danish")
val doe = Person("Doe", 23, "English","German")
val don = Person("Don", 11, "Italian","French","Polish")
val bob = Person("Bob", 17, "German")
//Access a property
joe.name
//Don had his 12th birthday!
don.age = 12
//Put the persons into a list
val persons = List(joe, doe, don, bob)
//Divide the list into minors and adults
val (minors, adults) = persons.partition(_.age < 18)
//Get the total age of all persons
val personsTotalAge = persons.map(_.age).sum
//Return a list with only those speaking English
val englishSpeakers = persons.filter(_.spokenLanguages.contains("English"))
//Same as the example above.
val englishSpeakers2 =
for{ person <- persons
language <- person.spokenLanguages
if language == "English"
} yield person
I'm not that fluent in C#, but I believe many things might look similar to you.
Some examples of Scala's XML support:
//The shoppingCart for breakfast
val shoppingCart = <list>
<item><name>Tomatoes</name><price>0.30</price><amount>4</amount></item>
<item><name>Eggs</name><price>0.15</price><amount>10</amount></item>
<item><name>Bread</name><price>2.20</price><amount>1</amount></item>
</list>
//How much does it cost?
val total = (shoppingCart \ "item").map(i => (i \ "price").text.toDouble * (i \ "amount").text.toDouble).sum
//This is a Symbol
val sym = 'SomeSymbol
//I'm too lazy to use Strings for XML! (Example for implicits)
implicit def symbol2string(symbol: Symbol) = symbol.name
//Now I can use Symbols too!
val total = (shoppingCart \ 'item).map(i => (i \ 'price).text.toDouble * (i \ 'amount).text.toDouble).sum

You don't need to learn Java first. Are you familiar with functional programming? If you are, you should be able to jump in quite fast. Anyway, here are some thoughts on how you can learn Scala:
Get a good reference book. I recommend Programming In Scala by Odersky, Spoon, and Venners. I find it as one of the most comprehensive Scala books.
As with learning any new language, try writing several small application using Scala. If you're not a functional programmer, you might program it in a different paradigm, but that's okay for now. Try writing your program without using "var, (use val instead)" not using loops, and minimizing state change overall.
Use sbt to build your program. I'm kinda hesitant to recommend this since you have to learn a new tool to write your program. But I find it a great too to write Scala apps with. And many Scala projects use sbt it seems like.
Also check out this comment and that thread overall to help you transition to Scala. Struggle against habits formed by Java when migrating to Scala

Java as a language will not be necessary to start with scala (and anyway java itself is very similar to c#, or actually it's the other way around...).
Once you start doing productive things with scala, though, you will be interacting with a lot of java libraries and learn that java-world is a much broader galaxy of more-or-less standard libraries than .net-world where a lots of the things you need are directly in the standard .NET libraries. You can learn them as you go, but not coming from a java background, the experience might feel overwhelming. It would be the same thing had you started learning java, though....
Other java-specific things you may have to learn are about generics being much less powerful in the JVM and how scala tries to work around this.
As for scala itself as a language, coming from .NET, you may benefit more from reading a few things on functional programming than from learning java. The functional paradigm is the part where I was the most ignorant in my initial approach to scala and that caused me the most trouble in understanding example code from the resources you can find on the scala website.
Building a foundation
For functional programming I would recommend reading SICP (it's online and free).
While you learn java try to take a look at F#. It's a good language, it's well documented and "lives" in the .NET ecosystem
learning scala
Resources on the scala website
Daniel Spiewak's blog

If you want to learn Scala, you'll be much better served by learning Scala and picking up the Java you need as you go. You don't need to learn Java to be able to start using Scala.
A good place to start would be reading through this question, which lists most of the Scala books currently available.
https://stackoverflow.com/questions/3359852/scala-programming-book/3360308#3360308

I don't think you need to know Java to get started on Scala. It's helpful to know the broad strokes though, because most Scala documentation I have read refers back to Java features or bugs.
Regarding Open Source projects, you cna have a look on Github for scala projects. Most open source Scala projects tend to be frameworks, though.
Regarding books, I found both the Artima book, Programming in Scala, and the Pragmatic Programmers, Programming Scala, very good.

In addition to the others: Write simple programs for a while and completely ignore advanced features of Scala. Only move there when you have a good grasp of the basics, the functional paradigm und the type system.

I advise you to take part in Coursera Functional Programming Principles in Scala by Martin Odersky. There are video lectures, assignments and even final exam.

Twitter (one of the scala lovers) recently unveiled their own scala complete tutorial -- Scala School. It is awesome guide which I recommend to all scala beginners.
Scala school was started as a series of lectures at Twitter to prepare
experienced engineers to be productive Scala programmers. ... We
think it makes the most sense to approach teaching Scala not as if
it's an improved Java but as a new language. Experience in Java is not
expected. Focus will be around the interpreter and the
object-functional style as well as the style of programming we do
here. An emphasis will be placed on maintainability, clarity of
expression, and leveraging the type system.
Most of the lessons require no software other than a Scala REPL. The
reader is encouraged to follow along, and go further! Use these
lessons as a starting point to explore the language.

I'm currently developing one which doesn't require prior programming knowledge. It will show the strength of combining functional and imperative programming, and it is very simple to follow. Furthermore, the posts will cover best practice and solve increasingly difficult problems using Scala.
http://vigtig.it/blog/
You should give it a try, part 2 is almost finished :)

Download and install Apache Maven. Use it to create a blank Scala project and write the classic Scala hello world application. This will require you to configure the pom.xml file in the project directory that Maven creates.
Then run mvn compile over and over, correcting errors until it compiles.
Then run mvn package until you pass all the unittests.
And finally, run mvn scala:run
Once you build a real project scala:run has an option to spit out the full Java command needed to run it from a shell script or batch file.

Related

Is there an equivalent of Haskell's CHP for Scala?

Clojure has this amazing library implementing Tony Hoare's Communicating Sequential Processes called core.async.
Haskell appears to have an equivalent called chp. (Not sure if it compiles under GHC 7.8).
My question is Is there an equivalent of Haskell's CHP for Scala?
You should have a look at this:
https://groups.google.com/forum/#!msg/scala-user/NljrQ4Mc-aI/3ISm68sqLNAJ
It provides a really interesting list of alternatives for doing CSP in Scala and doesn't recommend JCSP since it's development apparently stopped in 2011.
It also talks about a really interesting paper written by Andrew Bate at Oxford that describes a DSL in Scala for CSP but that whose implementation hasn't been open sourced.
It finally describes Quasar that seems the best alternative. If you're interested in Quasar, this post gives a good description of how Quasar works.

What parts of the Java ecosystem and language should a developer learn to get the most out of Scala?

Many of the available resources for learning Scala assume some background in Java. This can prove challenging for someone who is trying to learn Scala with no Java background.
What are some Java-isms a new Scala developer should know about as they learn the language?
For example, it's useful to know what a CLASSPATH is, what the java command line options are, etc...
That's a really great question! I've never thought about people learning Java just so they have it easier to learn Scala...
Apart from all the basics like for loops and such, learning Java Generics can be really helpful. The Scala equivalent is much more potent (and much harder to understand) than Java Generics. You might want to try to figure out where the limits of Java Generics are, and then in which cases Scala's type constructors can be used to overcome those limitations. At the more basic level, it is important to know why Generics are necessary, and how Java is a strongly typed language.
Java allows you to have multiple constructors for one class. This knowledge will be of no use when you learn Scala, because Scala has another way that allows you to offer several methods to create instances of a class. So, you'd rather not have a deep look into this Java concept.
Here are some concepts that differ very strongly between Java and Scala. So, if you learn the Java concepts and then later on want to learn the equivalent in Scala, you should be aware that the Scala equivalent differs so greatly from the Java version that a typical Java developer will have some difficulty to adapt to the Scala way of thinking. Still, it usually helps to first get used to the Java way, because it is usually simpler and easier to learn. I personally prefer to think of Java as the introductory course, and Scala is the pro version.
Java mutable collection concept vs. Scala mutable/immutable differentiation
static methods (Java) vs. singleton objects (Scala)
for loops
Java return statement vs. Scala functional style ("every expression returns a value")
Java's use of null for "no value" vs. Scala's more explicit Option type
imports
Java's switch vs. Scala's match
And here is a list of stuff that you will probably use from the Java standard library, even if you develop in Scala:
IO
GUI (Scala has a wrapper for Swing, but hey)
URLs, URIs, files
date
timers
And finally, some of Scala's features that have no direct equivalent in Java or the Java standard library:
operator overloading
implicits and implicit conversions
multiple argument lists / currying
anonymous functions / functions as values
actors
streams
Scala pattern matching (which rocks)
traits
type inference
for comprehensions
awesome collection operations like fold or map
Of course, all the lists are incomplete. That's just my view on what is important. I hope it helps.
And, by the way: You should definitely know about the class path and other JVM basics.
The standard library, above all else, because that's what Scala has most in common with Java.
You should also get a basic idea of Java's syntax, because a lot of books end up comparing something in Scala to something in Java. But other than the platform and some of the library, they're totally distinctive languages.
There are a few trivial conventions passed from one to the other (like command line options), but as you read books and tutorials on Scala you should pick those up as you go regardless of previous Java experience.
The serie "Scala for Java Refugees" can gives some indications on typical Java topics you are supposed to know and how they translate into Scala.
For instance, the very basic main() Java function which translate into the Application trait, once considered harmful, and now improved (for Scala 2.9 anyway).

What second language to use besides Scala for LowLevel? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I am absolutely happy with Scala and just love it :)
But sometimes I really want to go a bit more "low level", without a JVM and using "cool" CPU-Features like SSE etc.
So what would be a good second language besides Scala?
It should be:
Compiled to machine code
Easy usage of C-libraries
Possible to program very close to the hardware
Possible to program in a very highlevel-way when I want to
So basically I want a Scala where I can just throw in inline assembler when I want to :) I assume, that such a language does not exist, but maybe there are some that come close.
So what would be a good choice?
C++?, D?, OCaml?
I programmed a bit in C++ (15 Years ago) and very little with OCaml. In both cases, I only solved a few problems and never got very "deep" into the language itself.
You're pretty much describing D.
Compiled to machine code: Check. There is an experimental .NET VM implementation, but all three major implementations (DMD, LDC, GDC) compile directly to native code and the language is designed to make native compilation feasible.
Easy usage of C libraries: D supports the C ABI and all C types. Pretty much all you have to do is translate the header file and link in the C object file. This can even be partially automated.
Possible to program very close to the hardware: Check. D is what I'd call an idiomatic superset of C. It does not support every piece of C syntax, its module system is completely different, static arrays are value types in D2, etc. However, for any construct in the C language proper (i.e. excluding the preprocessor) there is an equivalent construct in D or the standard library. For any piece of C code (excluding preprocessor abuse) there is a canonical D translation that looks roughly the same and should generate the same assembly language instructions if you're using the same compiler backend. In other words, every C idiom (excluding preprocessor abuse) can be translated to D in a straightforward way.
The reference implementation of D also supports inline ASM, so you can mess with SSE, etc.
Possible to program in a very highlevel-way when I want to: Check. D is designed to be primarily garbage-collected language (though you can use manual memory management if you insist and are careful not to use library/runtime features that assume GC). Other than that, high-level programming is mostly implemented via template metaprogramming. Before you run away, please understand that template metaprogramming in D is greatly improved compared to C++. Doing template metaprogramming in D vs. C++ is like doing object oriented programming in C++ vs. C. In D template metaprogramming is designed into the language, whereas in C++ there are just enough features that you can use clever hackishness to make it barely work. The same could be said for object-oriented programming in C++ vs. C. The std.algorithm and std.range modules of Phobos are good examples of the high-level subset of D.
Here are some that satisfy the criteria mentioned in your question:
BitC
Clay
D
Rust
Go
I'm thinking about this, too, as I'm currently doing a C project and feeling very unproductive, also missing Scala. (I also did a lot of C++ in the Pleistocene...) I may switch to go. D also looks attractive.
Another option, if it makes sense for the problem, is to use C + a scripting language, like Lua or Ruby. It's what Unix+shells and emacs have done forever. You get performance and low-level bit twiddling when you need it and productivity when that's more important.
C++0X, Erlang and maybe Haskell and Go. C++ and Erlang has a strong user base and there is many jobs avaliable with C++0x and Erlang. (I am uncertain how good the C/C++ interop is with Go)
C++0X ("cee plus plus oh ex") is a good option. It has lamda functions and other good stuff.
Walktrough of C++0X TechDays 2010: Modern Programming with C++0x
Also C++0X has good Generics support as documented in Type Classes as Objects and Implicits, Oliviera, Moors, Odersky, OOPSLA 2010. See their Figure 12 below:
Something that fits your requirement is C/C++, as you can inline assembly language with regular code. Calling C libraries will be natural :)
Another thing that fits is the HLA implementation of assembly language (wiki article here) - it is assembly with a lot of high level constructs to make things easier (and faster) for beginners to learn (it compiles to "proper" native code).
Like D and BitC, ooc (http://www.ooc-lang.org/) has a lot of features that appeal to a Scala (or Haskell) fan.
I think Nimrod is also a valid candidate here based on your requirements.
You should take a look at Go.
It's still very new, but take a look at Vala. It's a sweet layer of syntactic frosting upon the GObject cake and compiled to pure C.
It supports features like closures and limited type inference.
Think about using C or C++ for the very lowest level programming, and then wrapping that with JNI or JNA in a Scala library. In some cases, you can have your cake and eat it too this way.

Scala AST in Scala [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
Is there a Scala library that parses Scala and creates an Abstract Syntax Tree (AST)?
Ideally I am interested in a Scala library. Plan B would be a Java library.
(I know I could leverage the EBNF from the Scala Syntax Summary.)
I would think the best way to access the AST is with a compiler plugin. You should read a soft introduction before diving in deep.
A few existing parsers:
The offical Scala compiler.
The IntelliJ IDEA Scala plugin has a parser written in Scala against IntelliJ's PsiBuilder API.
The Scala Netbeans plugin used a parser implemented in Rats! (which generates Java code), but "replaced these parser and analyzer by Scala's native compiler".
The Scala-rules project, written in Scala.
Be cautious if using the EBNF from the spec, there are apparently:
"mismatches between the appendix and the inline grammar, and mismatches between the language compiled by scalac (and utilized in the scala sources) and the language claimed by the grammar" -- Scala Trac bug #1826.
You can't build an AST for Scala from the grammar alone. There's implicits to consider, and, to consider them, there is the type inferencer to consider.
You can, however, call the compiler itself -- it is just a jar file, after all. Scala 2.8, in particular, has quite a few hooks for other programs to latch on -- work of Miles Sabin, who is doing this precisely so that the Eclipse plugin for Scala can leverage the compiler in such way.
I suggest you go to the Scala Tools mailing list, and get in contact with people there.
If you want to generate AST of a piece of code. You could use scala reflection:
showRaw(reify{
//your code here like:
print(2)
})
The code above will generate an AST:
Expr(Apply(Select(Ident(scala.Predef), TermName("print")), List(Literal(Constant(2)))))
Reference:
http://docs.scala-lang.org/overviews/reflection/symbols-trees-types.html
Here is a project by one of the compiler committers http://github.com/paulp/scala-lang-combinators
Not sure about the pure scala solutions, but if you find yourself needing to implement plan B, you can start by checking out ANTLR or Rats!

What is the purpose of Scala programming language? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
It is my opinion that every language was created for a specific purpose. What was Scala created for and what problems does it best solve?
One of the things mentioned in talks by Martin Odersky on Scala is it being a language which scales well to tackle various problems. He wasn't talking about scaling in the sense of performance but in the sense that the language itself can seem to be expanded via libraries. So that:
val lock = new ReentrantReadWriteLock
lock withReadLock {
//do stuff
}
Looks like there is some special syntactic sugar for dealing with j.u.c locks. But this is not the case, it's just using the scala language in such a way as it appears to be. The code is more readable, isn't it?
In particular the various parsing rules of the scala language make it very easy to create libraries which look like a domain-specific language (or DSL). Look at scala-test for example:
describe("MyCoolClass") {
it("should do cool stuff") {
val c = new MyCoolClass
c.prop should be ("cool")
}
}
(There are lots more examples of this - I found out this one yesterday). There is much talk about which new features are going in the Java language in JDK7 (project coin). Many of these features are special syntactic sugar to deal with some specific issue. Scala has been designed with some simple rules that mean new keywords for every little annoyance are not needed.
Another goal of Scala was to bridge the gap between functional and object-oriented languages. It contains many constructs inspired (i.e. copied from!) functional languages. I'm thing of the incredibly powerful pattern-matching, the actor-based concurrency framework and (of course) first- and higher-order functions.
Of course, your question said that there was a specific purpose and I've just given 3 separate reasons; you'll probably have to ask Martin Odersky!
One more of the original design goals was of course to create a language which runs on the Java Virtual Machine and is fully interoperable with Java classes. This has (at least) two advantages:
you can take advantage of the ubiquity, stability, features and reputation of the JVM. (think management extensions, JIT compilation, advanced Garbage Collection etc)
you can still use all your favourite Java libraries, both 3rd party and your own. If this wasn't the case, it would be a significant obstacle to using Scala commercially in many cases (mine for example).
Agree with previous answers but recommend the Introduction to An Overview of the Scala Programming Language:
The work on Scala stems from a research effort to develop better language support for component software. There are two hypotheses that we would like to validate with the Scala experiment. First, we postulate that a programming language for component software needs to be scalable in the sense that the same concepts can describe small as well as large parts. Therefore, we concentrate on mechanisms for abstraction, composition, and decomposition rather than adding a large set of primitives which might be useful for components at some level of scale, but not at other levels. Second, we postulate that scalable support for components can be provided by a programming language which unifes and generalizes object-oriented and functional programming. For statically typed languages, of which Scala is an instance, these two paradigms were up to now largely separate. (Odersky)
I'd personally classify Scala alongside Python in terms of which problems it solves and how. The conspicuous difference and occasional complaint is Type complexity. I agree Scala's abstractions are complicated and at times seemingly convoluted but for a few points:
They're also mostly optional.
Scala's compiler is like free testing and documentation as cyclomatic complexity and lines of code escalate.
When aptly implemented Scala can perform otherwise all but impossible operations behind consistent and coherent APIs. From Scala 2.8 Collections:
For instance, a String (or rather: its backing class RichString) can be seen as a sequence of Chars, yet it is not a generic collection type. Nevertheless, mapping a character to character map over a RichString should again yield a RichString, as in the following interaction with the Scala REPL:
scala> "abc" map (x => (x + 1).toChar)
res1: scala.runtime.RichString = bcd
But what happens if one applies a function from Char to Int to a string? In that case, we cannot produce a string as result, it has to be some sequence of Int elements instead. Indeed one gets:
"abc" map (x => (x + 1))
res2: scala.collection.immutable.Vector[Int] = Vector(98, 99, 100)
So it turns out that map yields different types depending on what the result type of the passed function argument is! (Odersky)
Since it's functional and uses actors (as I understand it, please comment if I've got this wrong) it makes it very easy to scale nearly anything up to any number of CPUs.
That said, I see Scala as kind of a test bed for new language features. Throw in the kitchen sink and see what happens.
My personal opinion is that for any apps involving a team of more than 3 people you are more productive with a language with Very Simple and Restrictive Syntax just because the entire job becomes more how you interact with others as opposed to just coding to make the computer do something.
The more people you add, the more time you are going to spend explaining what ?: means or the difference between | and || as applied to two booleans (In Java, you'll find very few people know).