Code Examples for

Programming in Scala, Third Edition

Return to chapter index

1 A Scalable Language

  • 1.1 A language that grows on you
  • 1.2 What makes Scala scalable?
  • 1.3 Why Scala?
  • 1.4 Scala's roots
  • 1.5 Conclusion
  • 1.1 A language that grows on you


    var capital = Map("US" -> "Washington", "France" -> "Paris") capital += ("Japan" -> "Tokyo") println(capital("France"))
    def factorial(x: BigInt): BigInt = if (x == 0) 1 else x * factorial(x - 1)
    265252859812191058636308480000000
    import java.math.BigInteger def factorial(x: BigInteger): BigInteger = if (x == BigInteger.ZERO) BigInteger.ONE else x.multiply(factorial(x.subtract(BigInteger.ONE)))
    recipient ! msg
    def receive = { case Msg1 => ... // handle Msg1 case Msg2 => ... // handle Msg2 // ... }
    class ChecksumActor extends Actor { var sum = 0 def receive = { case Data(byte) => sum += byte case GetChecksum(requester) => val checksum = ~(sum & 0xFF) + 1 requester ! checksum } }

    1.2 What makes Scala scalable?


    val xs = 1 to 3 val it = xs.iterator eventually { it.next() shouldBe 3 }

    1.3 Why Scala?


    // this is Java class MyClass { private int index; private String name; public MyClass(int index, String name) { this.index = index; this.name = name; } }
    class MyClass(index: Int, name: String)
    boolean nameHasUpperCase = false; // this is Java for (int i = 0; i < name.length(); ++i) { if (Character.isUpperCase(name.charAt(i))) { nameHasUpperCase = true; break; } }
    val nameHasUpperCase = name.exists(_.isUpper)
    boolean nameHasUpperCase = // This is Java 8 name.chars().anyMatch( (int ch) -> Character.isUpperCase((char) ch) );
    s.exists(p) || s.exists(q) == s.exists(x => p(x) || q(x))
    def f(x: String) = ...
    val x: HashMap[Int, String] = new HashMap[Int, String]()
    val x = new HashMap[Int, String]() val x: Map[Int, String] = new HashMap()

    1.4 Scala's roots

    1.5 Conclusion

    For more information about Programming in Scala, Third Edition (the "Stairway Book"), please visit:

    http://www.artima.com/shop/programming_in_scala_3ed

    and:

    http://booksites.artima.com/programming_in_scala_3ed

    Copyright © 2007-2016 Artima, Inc. All rights reserved.

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.