CSC447

Concepts of Programming Languages

Scala Pragmatics

Instructor: James Riely

Get Java and Scala

  • Unzip the Scala homework workspace from here
  • Follow the instructions in README.html
  • Install Java LTS (long term support)
  • Install SBT using the windows installer or homebrew.

Using scala

  • For real programs and homeworks, use sbt to run tests
    • file may only contain object and class declarations
      
      object o { val x = ... }
      class c { ... }
                        
    • You can use console/:quit to get a REPL within sbt
    • In the sbt REPL, you can use import objects
      
      import o._
      // use x
                        

Using scala

  • For tiny examples, type directly into the REPL
    
    val x = ... 
    // use x
                  

Using scala

  • For larger examples, type in a file and paste into the REPL
    
    :paste /Users/jriely/x.scala
    // use x
                  
    • File contains declarations just as you would type them in the REPL
    • If there are expressions, then the last one is printed out as a value in the REPL.
    • Do not put the file x.scala in the SBT directory. If you do, then SBT will try to compile it and give you an error, since SBT requires files to contain only object and class declarations.
    • I put x.scala in my home directory (/Users/jriely/), or in /tmp/.

Disassembly

  • To see what scala is doing, you can disassemble in the REPL
    
    scala> class C { val x:Int = 1}
    defined class C
    
    scala> :javap -p -c -filter C
    Compiled from "<console>"
    public class C {
      private final int x;
    
      public int x();
        Code:
           0: aload_0
           1: getfield      #18                 // Field x:I
           4: ireturn
    
      public C();
        Code:
           0: aload_0
           1: invokespecial #24                 // Method java/lang/Object."<init>":()V
           4: aload_0
           5: iconst_1
           6: putfield      #18                 // Field x:I
           9: return
    }
                  

Disassembly

  • You can also see the previous REPL delcaration
    
    scala> def x = 1
    x: Int
    
    scala> :javap -p -c -filter -
    Compiled from "<console>"
    public class  {
      public static  MODULE$;
    
      public static {};
        Code:
           0: new           #2                  // class 
           3: invokespecial #17                 // Method "<init>":()V
           6: return
    
      public int x();
        Code:
           0: iconst_1
           1: ireturn
    
      public ();
        Code:
           0: aload_0
           1: invokespecial #21                 // Method java/lang/Object."<init>":()V
           4: aload_0
           5: putstatic     #23                 // Field MODULE$:L;
           8: return
    }
                  

Homework

  • testOnly fp1tests
  • testOnly fp1tests -- -n fp1ex05
  • ~testOnly fp1tests