Scala, Play 2.0 & Cloud Foundry


Published on

Introduction to Scala, Functional Programming, Play 2.0 and Cloud Foundry

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • scalable bcoz ..easy-to-use libraries that feel like native language support add new types that can be used as conveniently as built-in types. “grow” the Scala language in new directions even as specialized as concurrent programming. use java’s rich, thread-based concurrency library and additional library that implements Erlang’s actor model Even though they are defined in a library, actors feel like an integral part of the Scala language.
  • the one thing that makes it scalable is unification of functions and objects
  • Simula in the mid-60’s and Smalltalk in the 70’s object is container – data and operationsNo primitive types at java level but handles JVM primitive types at bytecode level
  • What is Functional programming ?before understanding how FP is implemeneted in scala, let us first understand what FP is ?
  • first was Lisp in late 50s. Other popular are Erlang, Haskell, OCaml, and F#.
  • Def: keywordFunction nameParameter listColonReturn type [optional; compiler can infer it from the context ]Equal toFunction bodyVal – FP concept Var – OO concept
  • diamond inheritance” is when the same class is inherited via several different paths.
  • Collection c;On compl work,
  • No semicolonComparing Class and constructor in java with scala With use of Functional literals, avoid use of loops  Type inference- no need to specify types,optionalParameterize type, combine types, hide details,Build our own types, design interfaces Each variable, method parameter, return type etc. has a type known at compile time, either declared or inferred like java,c,c++.
  • Scala, Play 2.0 & Cloud Foundry

    1. 1. “Scala, Play 2.0 & Cloud Foundry” By: Pray Desai Intern – Scala Developer Advocate Cloud Foundry @praydesai
    2. 2. Scala
    3. 3. Introduction• Scala is a programming language that combines features of object-oriented programming with functional programming.• Scala (skah-la) stands for Scalable language• Designed to grow with the demands of users• Growing new types by defining easy-to-use libraries• Growing new control constructs such as concurrent programming• Write small scripts as well as build large systems
    4. 4. • Scala runs on the Java platform (Java Virtual Machine) as well as Dot Net platform.• Designed by Martin Odersky in 2001 at EPFL, who was also one of the creators of javac compiler and generic java• Open source• Released in 2004• Second version v 2.0 in 2006• Current version is 2.9.2
    5. 5. Q : What is the one thing that makes Scala scalable ? Ans.: Combining OO with FP
    6. 6. Object Oriented programming• Purely OO• Every value is an object• Every operation is a method• No primitive types, everything is object• 1 + 2 invokes a method + defined in class Int
    7. 7. Functional programming• Not purely FP
    8. 8. What is Functional programming ?• Concept came from Lambda Calculus• Computation by evaluation of functions• Basic fundamental is to evaluate an expression and use its result for some other expression• Made up of functions that always return some value• Char of FP absent in IP & OO : Always return same value for same inputs ; map input values to output values• No side effects : state does not change• Immutable data : Cannot change the value once set; so no need to lock the access of shared data• Reuse same code in diff parts of the programs• Free order of code execution
    9. 9. Functional programming in Scala• Partially FP• Supports mutable data as well as immutable• Variables as well as Values• Functions are first-class values just like an integer or string• Higher – order functions: allows to combine parts of code easily• Pass functions as arguments to other functions• Return functions as results from functions• Store functions in variables• Define a function inside another function• Closures - functions that capture variables defined in scope. Function can access variable even after scope is exited.• Modern Collection Library that allows parallel execution of functions• Supports immutable data structures in its libraries so no need of locks to access.
    10. 10. Syntax The implementation is similar to Java or C. We use the same operators and control structures.• Function definition starts with “def” def fact(x:Int) : Int = if(x==0)1 else x*fact(x-1)• variable definitions start with “var” and definitions of values (i.e. read only variables) start with “val”.• val is immutable where var is mutable Error : Correct: val x=123 var x=123 x=x+1 x=x+1• No need to write public. It is default visibility.• No semicolon• No need to specify data type, compiler infers it from context• Array types are written as Array[Int] rather than Int[], and array selections are written a(i) rather than a[i].• Looping becomes easy with the use of functional literals for (i<-0 to 10) print(i) for (I <-0 until 10) print(i)
    11. 11. Comparison with Java• It is compatible with existing Java programs and we can use all java libraries.• Its operates similar to Java. Its compiler generates byte code that is similar to java bytecode• JVM cannot differentiate between scala code and java code. The only difference is an extra runtime library.• Scala code can be decompiled to readable Java code, with the exception of certain constructor operations.• Runs on Eclipse and Netbeans IDE just as Java.• The only two things in scala which are absent in java are richer type system and support for functional programming.
    12. 12. Traits• Traits are like interfaces in java but can also have method implementations and fields which can then be reused by mixing them into classes.• Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits.• Members of class are added to members of multiple traits• Avoids diamond problem in multiple inheritance• Automatically add methods to a class in terms of methods the class already has.• Make a thin interface into a rich one.
    13. 13. Abstract Class• Class abstractions are extended by subclassing abstract class class1 extends trait1 { case subclass1 extends class1 case subclass2 extends class1 }
    14. 14. No getters and setterspublic class Person{ private String firstName = null; public class Person { private String lastName = null; var firstName = "" private int age = 0; var lastName = "" var age = 0 public void setFirstName(String }firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(StringlastName) { this.lastName = lastName; } public String getLastName() { developers-should-be-learning-scala/ return lastName;
    15. 15. Data Structures [Containers of values]1. List• Collection of data that can be randomly accessed and can have different datatypes• Immutable, new list generated every time• Int list : val a =List(1,2,3)• Combination : val b =List(“a”,’’b”,4)• Concate lists : a ::: b• Any is catchall datatype• Access value: b(2)
    16. 16. 2. Set• Similar to list but independent of order• Cannot combine datatypes in single set• Immutable, new set generated everytime• Set(1,2,3) == Set(3,1,2) true• List(1,2,3)==List(3,1,2) false var a = Set(1,2,3) val b = Set(0,1,5)• Add/remove value from set : a=a+4 a=a-3• Union : a ++ b• Intersection : a ** b
    17. 17. 3. Map• Key-value pair which maps keys of type A to values of type Bval m = Map (0 -> “abc”, 1->”def”, 2->”xyz”)m(2)
    18. 18. 4. Tuple• Store different data types in same variable• Used to return multiple objects from method• Storing/Retrieving rows of tables in database val address=(201,”s 4 th st”) address (._1) address (._2) address
    19. 19. Pattern Matching• Conditionally execute code based on some data provided• Used in parsing xml and parsing messages between threads• Similar to switch case, no breaks• def chek(a:Int) { a match case 0 => … case 1 => .. case _ => .. }
    20. 20. Support to Parallel Processing• In v2.9, collections support parallel operations• It has two methods : c.par which returns parallel version of c c.seq which returns sequential version of c• Divide work by number of processors• Threads maintain work queues
    21. 21. Actors• Actors are basic units of concurrency implemented on top of threads.• Two basic operations: message send and receive.• A send is asynchronous without waiting for the message to be received and processed• Every actor has a mailbox in which incoming messages are queued.• A receive block consists of a number of cases that each query the mailbox with a message pattern.• The first message in the mailbox that matches any of the cases is selected, and the corresponding action is performed on it.
    22. 22. Scala features in Java 8• Lambda expressions• Higher order functions• Parallel Collections• Function chaining• Traits
    23. 23. Lambda expressionsFunction Literal• Function with input parameters and function body• (type parameter) -> function_body• ex: (String s1, String s2) - > s1.length()- s2.length();
    24. 24. Why Scala ?• Compatible - with JVM• Concise - reduced code //java //scala class student { class student(id:Int, name:String) private int id; private String name; public student (int id, String name) { = id; = name; }}• High-level - more simpler, shorter code and easy to understand, Use and design libraries for clear and concise code• Statically typed – variable type known at compile time, less runtime errors• XML literals - create and consuming XML quite easy within your applications.• Parallel Processing - .par, .seq, Actors
    25. 25. Testing There are several ways to test code in Scala :• ScalaTest Supports multiple testing styles and can integrate with Java-based testing frameworks• ScalaCheck Generates automatic test case and minimizes failing test cases• Specs2 Library for writing executable software specifications• ScalaMock Provides support for testing high-order and curried functions• JUnit , TestNG Unit testing frameworks for java• Borachio Provides support for testing high-order and curried functions.
    26. 26. Companies that work on Scala• Twitter - for queuing system that handles heavy load• LinkedIn – used in their framework “Nobert”• Sony -library that manages updates, rollbacks and changes to database schemas• Siemens – application for company wide employees communication to boost productivity• Xerox – to improve customer experience• Grid Grain - provides DSL for cloud computing• Swiss bank UBS - for general production usage• FourSquare - for message passing• The Guardian newspaper - content API for selecting and collecting news content• Juniper Networks – distributed software based on Akka middleware for multi-core processors
    27. 27. Limitations• Syntax Difficult to understand as reading backwards. The return value is at the end of the declaration, and the types are declared after the variable names.• Slow compilation and interpreter Takes much time to compile and run. We can use fsc compiler now (Fast Scala Compiler), which essentially stays resident in memory.
    28. 28. Further Enhancements• Developer tools- Akka/Scala stack, Akka framework, which is the most widely used parallel computation framework on top of Java• Style-checking tool, to be integrated in next release of the IDE.• Visual Studio integration.• Scala for JavaScript• V2.10 : better support for dynamic languages, better reflection, better support for parallelism.
    29. 29. Conclusion• “If I were to pick a language to use on JVM other than Java then it would be Scala” – James Gosling• “Scala will be long term replacement of java, If someone had told me about Scala then I would have never created Groovy” – James Strachan , Creator of Groovy• “Scala is current heir apparent to Java throne, no other language capable to replace java than scala” – Charlies Nutter, JRuby Lead
    30. 30. Scala Resources• Programming in Scala, 2nd edition by Martin Odersky••• Free Online Course from 9/18/2012 for 7 weeks:
    31. 31. Installing Scala in Eclipse• Current versions: IDE: 2.0.2 Scala: 2.9.x• Required: JDK 5 or 6, Eclipse Helios or Indigo•• Copy the url for the current version• Help -> Install New Software OR• Search Scala IDE in Help -> Eclipse Market Place
    32. 32. Hello World Programobject Hello { def main (args: Array[String]) { println("Hello World") }}
    33. 33. Play 2.0
    34. 34. Play 2.0• Web application framework• MVC• Light-weight• Core written in Scala• Local Host Server• No need to add any external jars !• Display errors in browser
    35. 35. Installing Play 2.0• Required: JDK 6• Download from• Unzip and add play directory to working path• For Mac : export PATH=$PATH:/Applications/play-2.0• For Windows: Set path in the global environment variable
    36. 36. Play commands• Check Play is installed play help• Create a new Play app play new <app-name> cd <app-name>• Run the app play run Go to browser and type - localhost:9000 Ctrl + D to stop server• Clean the server play clean
    37. 37. Play in Eclipse• play eclipsify• File -> Import -> Existing Projects into WS
    38. 38. Working Directory• app  controllers  view  model• test• conf  application.conf  routes• logs• project• public  images  javascripts  stylesheets
    39. 39. Hello World Appcontrollers/Application.scala views/index.scala.htmlpackage controllers @(message: String)import play.api._import play.api.mvc._ @main("Welcome") { @messageobject Application extends Controller { } def index = Action { Ok(views.html.index("Hello World")) }}
    40. 40. Configure routes conf/routes# Home pageGET / controllers.Application.index# Map static resources from the /public folder to /assets URL pathGET /assets/*file"/public", file)
    41. 41. Play 2.0 Resources• Go to the directory where you installed Play play-2.0/documentation/Play 2.0 Doc.pdf• Sample apps : play-2.0/samples/scala• n/2.0.2/ScalaHome
    42. 42. Cloud Foundry
    43. 43. What is Cloud Foundry ?• Open PaaS• “Linux of the Cloud”• Deploy and scale apps easily• Focus just on coding• Supports Scala & Play 2.0• Choice of many other services and frameworks
    44. 44. Register•• Get your credentails in email Welcome email 28• Check your login on
    45. 45. Install RVM and Ruby For Mac:• Install Ruby Version Manager• rvm install 1.9.2• rvm use 1.9.2
    46. 46. For Windows:• Download version 1.9.2• Check version by ruby –v
    47. 47. Install vmc [command line tool]• gem install vmc• Check version (0.3.18 or higher) vmc –v• vmc login• vmc target
    48. 48. Deploy Play App on Cloud Foundry• Package app cd app1 play clean distYour application is ready in/Users/desaip/app1/dist/• vmc push --path=dist/
    49. 49. vmc push [to deploy app for the first time]desaip-mbp:~ desaip$ cd check1desaip-mbp:check1 desaip$ vmc push --path=dist/check1-1.0-SNAPSHOT.zipApplication Name: check1Detected a Play Framework Application, is this correct? [Yn]:Application Deployed URL []:Memory reservation (128M, 256M, 512M, 1G, 2G) [256M]:How many instances? [1]:Create services to bind to check1? [yN]: NWould you like to save this configuration? [yN]: NCreating Application: OKUploading Application: Checking for available resources: OK Processing resources: OK Packing application: OK Uploading (80K): OKPush Status: OKStaging Application check1: OKStarting Application check1: OKdesaip-mbp:check1 desaip$
    50. 50. vmc update [ to deploy updated app]• cd app1• play clean dist• vmc update app1 --path=dist/app1-1.0-SNAPSHOT.zipdesaip-mbp:check1 desaip$ vmc update check1 --path=dist/check1-1.0-SNAPSHOT.zipUploading Application: Checking for available resources: OK Processing resources: OK Packing application: OK Uploading (80K): OKPush Status: OKStopping Application check1: OKStaging Application check1: OKStarting Application check1: OKdesaip-mbp:check1 desaip$
    51. 51. vmc instances [ to scale your app]• To create another instance vmc instances <app-name> +1• To see other commands vmc help
    52. 52. Cloud Foundry Resources• ud-foundry-now-supports-play/• cloud-foundry-bootcamp-at-contributingcode• started-with-cloud-foundry-part-13/
    53. 53. THANK YOU