1. Making sense of
& other JVM languages
Praveen Manvi
November 2012
2. whoami
• Currently working as Senior Technologist @ Thomson Reuters
• 13 + years java development experience
• Focused on API design, middleware, desktop ,web application
frameworks
• Used Groovy/Scala for personal/internal projects but NOT
professionally
• The material here are strictly personal opinions with limited
functional programming exposure & understood by internet
literature .Consider what you like & disdain others
• Created http://JavaIQ.in in play framework as personal
project
3. Purpose of this presentation
Introduce Scala language to Java developers
Hope to convince that scala solves many of Java's
design/coding problems.
Explain how some other JVM languages stack against Scala
particularly Groovy where-ever applicable.
However -
Its NOT a comprehensive overview on scala
4. What is Scala?
Scala is a new programming language for the Java Virtual Machine. It
combines advanced object-oriented and functional concepts which will
give enormous productivity and expressiveness benefits over Java.
Scala is fully interoperable with Java, preserving existing investments in
software, tools and skills.
Key Differentiator from other JVM languages:
Allows to write succinct programs without losing type safety and
performance in both object oriented and functional style.
5. History
Scalable Language – 2006 (same principles for small to large)
The language is so named because it was
designed to grow with the demands of
users
Martin Odersky - Creator
6. What Experts say …
“I can honestly say if someone had shown me
the Programming Scala book by by Martin
Odersky, Lex Spoon & Bill Venners back in 2003
I’d probably have never created Groovy.” –
James Strachan.
“If I were to pick a language to use today other
than Java, it would be scala” - James Gosling
“I think Scala is the only current language likely
to take the throne from Java” - Charles Oliver
Nutter (JRuby Creator)
7. Salient Features
Speed/Safety of a static language
Clean syntax, expressive power, type inference
Pure object-orientation (Everything is an Object)
Support for concise functional programming
Scalability to large industrial-scale systems
Pattern matching
XML support such as XML literals in code
8. Ceremony vs Essence
Get the minors from the list List<Person> people
List<Person> minors(List<Person> people) {
List<Person> result = new ArrayList<Person>();
for (Person person : people) {
if (person.age() <= 18) {
result.add(person);
}
}
return result;
}
val minors = people.filter(_.age <= 18)
def minors = people.filter { p -> p.age <= 18 }
“succinctness is power” - http://www.paulgraham.com/power.html
9. Fixing Java Day Today Issues
Native XML support
def page(name: String, format: String) = Action {
Ok(<p>You requested page {name} in format {format}</p>.toString).as(HTML)
}
Case class for type safe immutable objects
case class Person(firstName: String,lastName:String , age:Int, salaryIn$:Int, skills:Array[String])
new Person("Praveen", "Manvi", 35, 40000, Array("Java Script", "Java", "Scala", "Groovy")),
new Person(firstName="Prasanna", "Manvi", 40, 90000,
Array("C", "Pascal", "C++")),
Functional Java Collections with fluent API
val (passed, failed) = List(49, 31, 58, 76, 82, 88, 90) partition ( _ > 60 )
10. Fixing Java Day Today Issues…
Multi-line String
SQL( """ select * from Country c join CountryLanguage l
on l.CountryCode = c.Code where c
.code = {countryCode};
""" ).on("countryCode" -> "FRA")
Packages can be nested & imports can be in
methods
package out {
class Main { ... }
package inner {
class Helper { ... }
}
}
11. Fixing Java Day Today Issues…
Import statements
Multiple classes
import java.util.{Date, Collection, List}
Renaming the classes
import java.util.{Collection => JavaCollection}
Import classses anywhere in the document
Pattern Matching
def match(x: Int): String =
x match {
case 0 => “none”
case 1 => “one”
case 2 => “two”
case _ => “many”
}
12. Fixing Java Day Today Issues…
Handling exceptions
val PORT = try System.getProperty(“PORT", "8080").toInt catch { case e: NumberFormatException => 8080 }
Passing default/named parameters
/** override only the loadFactory via
named arguments
*/
val m4 = new HashMap[String,Int](loadFactor = 0.8)
Singleton class
/**
* object creates
*/
object Main {
}
13. Fixing Java Day Today Issues…
Handling Null
def createPerson(name:String, age:Int, ethnicity:Option[String]) = {
storeInDatabase(name,age,ethnicity.getOrElse("U").charAt(0))
}
Adding methods to existing class
case User(name:String,pwd:String)
implicit UserWrapper(val u:User) extends AnyVal
def isAdmin = u.name.equals(“admin”)
14. Less boiler plate code
No need to use external libraries to avoid, more
importantly fluency is part of language
- Apache commons – IO, String manipulation
- Guava – Collections
- Function Java
- Java 7 – File APIs, resource handling
We don’t have resolve special tricks (Predicate,
anonymous classes) to get this benefit
So, Its about mindset change not just the keystrokes
savings
15. Java – 8 lambda
No more anonymous classes
class UIBuilder { public UIBuilder() {
button.addActionListener(e -> //process ActionEvent e)
}}
16. Scala == effective Java
• Favor Immutability
• Avoid Null references
• Type safe objects
• Consider static factory methods & builder
pattern instead of long constructor
17. DSL in scala
New language can be defined
to buy(200 sharesOf "GOOGLE")
maxUnitPrice 300
using defaultPricing
if a programming language is sufficiently powerful,
then 'your fantasy is the limit'
18. Multi core programming
“Single-core performance is running out of steam, and you need
to parallelize everything,”
Make collections go parallel
val people: Array[Person]
val(minors, adults) = people.par partition(_.age<18)
19. Interesting new (& enhanced)
concepts
• Inheritance
– Sealed Vs final
– Traits Vs interfaces
• Generics & Operator overloading
– val list = new ListBuffer[String]
– list+=“praveen”
20. Functional Programming
• Assignment less programming
• Immutable state
• Functions as basic building blocs
• Programming with expressions - transforming
of data
21. Closures and Currying
val multiply = { final int x, final int y -> x * y }
// twice:: Integer -> Integer
final twice = multiply.curry(2)
// quadruple:: Integer -> Integer
final quadruple = multiply.curry(4)
assert twice(5) == 10
assert quadruple(5) == 20
23. Final comments
• Scala is not just a “Java++”.
– its different and you can get into any depth level,
everyday you will get surprised.
– Kingdom of nouns Vs Kingdom of Verbs
24. Scala is like “Dragon” in Avatar
It will frighten in the beginning…
25. But once you are trained…
It will be awesome experience to ride
27. Feature List
• is an agile and dynamic language for the Java
Virtual Machine
• builds upon the strengths of Java but
has additional power features inspired by
languages like Python, Ruby and Smalltalk
• makes modern programming
features available to Java developers
with almost-zero learning curve.#1 choice for
java progrmmers
28. Feature List
• provides the ability to statically type
check and statically compile your code
• supports Domain-Specific Languages and
other compact syntax so your code
becomes easy to read and maintain
• makes writing shell and build scripts easy with
its powerful processing primitives, OO
abilities and an DSL for build systems
29. Feature List
• increases developer productivity by reducing
scaffolding code when developing web, GUI,
database or console applications
• simplifies testing by supporting unit testing
and mocking out-of-the-box
• seamlessly integrates with all existing Java
classes and libraries