This link has been bookmarked by 215 people and liked by 1 people. It was first bookmarked on 17 May 2007, by ciukes ..
-
06 Jun 17
-
19 Sep 14
-
statically typed, object-oriented
-
The main Scala compiler,
scalac, generates Java class files that can be run on the JVM. However, another Scala compiler exists that generates binaries that can be run on the .NET CLR -
It has the conciseness of a dynamic language like Ruby or Python, but it is statically typed, like Java.
-
The type
Intnames the classIntin the packagescala. Values of this class are implemented just like Java'sintvalues. In fact, Scala treatsintas an alias forscala.Int -
More generally, all of Java's primitive types are defined as aliases for classes in the
scalapackage. -
The type of the result here is
scala.Unit, which is Scala's analogue tovoidin Java. The main difference between Scala'sUnitand Java'svoidis that Scala lets you write down a value of typeUnit, namely(), whereas in Java there is no value of typevoid -
()is the one and only value of typeUnitin Scala -
Scala differentiates between
vals, variables that are assigned once and never change, andvars, variables that may change over their lifetime -
because Scala strings are also Java strings. (In fact every Java class is available in Scala.)
-
This example also points out an important and very useful feature of Scala: type inference. Notice that you never said the word
java.lang.Stringor evenStringin thevaldefinition -
In contrast to Java, where you specify a variable&8217;s type before its name, in Scala you specify a variable's type after its name, separated by a colon.
-
scala> val msg2: java.lang.String = "Hello again, world!" msg2: java.lang.String = Hello, world!
-
def max(x: Int, y: Int): Int = if (x < y) y else x
-
A type annotation must follow every method parameter, preceded by a colon in the Scala way, because the Scala compiler (and interpreter, but from now on we'll just say compiler) does not infer method parameter types.
-
the method is recursive1, for example, you must explicitly specify the method result type. In the case of
maxhowever, you may leave the result type specifier off and the compiler will infer it. -
Since
max's body consists of just one statement, you need not place it inside curly braces, but you can if you want. So you could also have written: -
If you want to put more than one statement in the body of a method, you must enclose them inside curly braces.
-
def greet() = println("Hello, world!")
-
but you access an element by specifying an index in parentheses rather than square brackets. So the first element in a Scala array named
stepsissteps(0), notsteps[0] -
// Say hello to the first argument println("Hello, " + args(0) + "!")
-
The expression
"Hello, " + "world!"will result in the string"Hello, world!". -
#!/bin/sh exec scala $0 $@ !# // Say hello to the first argument println("Hello, " + args(0) + "!")
-
var i = 0 while (i < args.length) { println(args(i)) i += 1 }
-
var i = 0 while (i < args.length) { if (i != 0) print(" ") print(args(i)) i += 1 } println()
-
Note that in Scala, as in Java, you must put the boolean expression for a
whileor anifin parentheses. -
Scala does use semi-colons to separate statements as in Java, except that in Scala the semi-colons are very often optional, giving some welcome relief to your right pinky finger
-
For example, another (far more concise) way to print each command line argument is:
args.foreach(arg => println(arg))
-
In this case, you're passing in an anonymous function (one with no name), which takes one parameter named
arg -
If you'd prefer to be more explicit
-
the Scala interpreter infers type of
argto beString -
If an anonymous function consists of one method application that takes a single argument, you need not explicitly name and specify the argument
-
args.foreach(println)
-
To summarize, the syntax for an anonymous function is a list of named parameters, in parentheses, a right arrow, and then the body of the function.
-

Figure 1. The syntax of a Scala anonymous function. -
In an effort to guide you in a functional direction, only a functional relative of the imperative
for(called a for comprehension) is available in Scala. -
for (arg <- args) println(arg)
-
In addition to being functional, Scala is object-oriented.
-
In the previous example, you parameterize the
Stringinstance with the initial value"Hello, world!". You can think of parameterization as meaning configuring an instance at the point in your program that you create that instance -
The main difference is that instead of the angle brackets used for this purpose in Java, in Scala you use square brackets
-
val greetStrings = new Array[String](3) greetStrings(0) = "Hello" greetStrings(1) = ", " greetStrings(2) = "world! " for (i <- 0 to 2) print(greetStrings(i))
-
val greetStrings: Array[String] = new Array[String](3)
-
When you define a variable with
val, the variable can't be reassigned, but the object to which it refers could potentially still be mutated. So in this case, you couldn't reassigngreetStringsto a different array;greetStringswill always point to the sameArray[String]instance with which it was initialized. But you can change the elements of thatArray[String]over time, -
for (i <- 0 to 2) print(greetStrings(i))
-
The first line of code in this for comprehension illustrates another general rule of Scala: if a method takes only one parameter, you can call it without a dot or parentheses.
tois actually a method that takes oneIntargument -
The code
0 to 2is transformed into the method call0.to(2). -
(This
tomethod actually returns not anArraybut a Scala iterator that returns the values 0, 1, and 2.) -
Arrays are simply instances of classes like any other class in Scala. When you apply parentheses to a variable and pass in some arguments, Scala will transform that into an invocation of a method named
apply. SogreetStrings(i)gets transformed intogreetStrings.apply(i). -
Similarly, when an assignment is made to a variable that is followed by some arguments in parentheses, the compiler will transform that into an invocation of an
updatemethod that takes two parameters. For example,greetStrings(0) = "Hello"
-
greetStrings.update(0, "Hello")
-
However, it is significant to note that in Scala this uniformity does not usually come with a performance cost as it often has in other languages that have aimed to be pure in their object orientation.
-
the conceptual simplicity of a pure object-oriented language with the runtime performance characteristics of language that has special cases for performance reasons.
-
Another benefit of the functional style in a statically typed language is that everything that goes into and out of a method is checked by a type checker, so logic errors are more likely to manifest themselves as type errors.
-
If you create a
Stringwith the value"Hello, ", it will keep that value for the rest of its lifetime. If you later callconcat("world!")on thatString, it will not add"world!"to itself. Instead, it will create and return a brand newStringwith the valueHello, world!". -
a Scala
Arrayis a mutable sequence of objects that all share the same type -
Thus,
Arrays are mutable objects. An immutable, and therefore more functional-oriented, sequence of objects that share the same type is Scala'sList. As withArrays, aList[String]contains onlyStrings. Scala'sList,scala.List, differs from Java'sjava.util.Listtype in that ScalaLists are always immutable (whereas JavaLists can be mutable). But more importantly, Scala'sListis designed to enable a functional style of programming. -
val oneTwoThree = List(1, 2, 3)
-
(You don't need to say
new Listbecause “List” is defined as a factory method on thescala.Listsingleton object. More on Scala's singleton object construct in Step 11.) -
Listhas a method named:::that concatenates a passedListand theListon which:::was invoked. -
Perhaps the most common operator you'll use with
Lists is::, which is pronounced “cons.” Cons prepends a new element to the beginning of an existingList, and returns the resultingList -
val twoThree = List(2, 3) val oneTwoThree = 1 :: twoThree println(oneTwoThree)
-
Given that a shorthand way to specify an empty
ListisNil -
val oneTwoThree = 1 :: 2 :: 3 :: Nil
-
thrill.count(s => s.length == 4)Counts the number of Stringelements inthrillthat have length 4 (returns 2) -
thrill.drop(2)Returns the thrillListwithout its first 2 elements (returnsList("until"))thrill.dropRight(2)Returns the thrillListwithout its rightmost 2 elements (returnsList("Will")) -
thrill.filter(s => s.length == 4)Returns a Listof all elements, in order, of thethrillListthat have length 4 (returnsList("Will", "fill")) -
thrill.forall(s => s.endsWith("l"))Indicates whether all elements in the thrillListend with the letter"l"(returnstrue)thrill.foreach(s => print(s))Executes the printstatement on each of theStrings in thethrillList(prints"Willfilluntil") -
thrill.map(s => s + "y")Returns a Listresulting from adding a"y"to eachStringelement in thethrillList(returnsList("Willy", "filly", "untily"))thrill.remove(s => s.length == 4)Returns a Listof all elements, in order, of thethrillListexcept those that have length 4 (returnsList("until")) -
thrill.tailReturns the thrillListminus its first element (returnsList("fill", "until")) -
Besides
List, one other ordered collection of object elements that's very useful in Scala is the tuple. LikeLists, tuples are immutable, but unlikeLists, tuples can contain different types of elements. Thus whereas a list might be aList[Int]or aList[String], a tuple could contain both anIntand aStringat the same time. -
And it is simple: to instantiate a new tuple that holds some objects, just place the objects in parentheses, separated by commas. Once you have a tuple instantiated, you can access its elements individually with a dot, underscore, and the one-based index of the element.
-
val pair = (99, "Luftballons") println(pair._1) println(pair._2)
-
Scala infers the type of the tuple to be
Tuple2[Int, String], and gives that type to the variablepairas well -
When it comes to
Sets andMaps, Scala also provides mutable and immutable alternatives, but in a different way. ForSets andMaps, Scala models mutability in the class hierarchy. -
For example, the Scala API contains a base trait for
Sets, where a trait is similar to a Javainterface. (You'll find out more abouttraits in Step 12.) Scala then provides two subtraits, one for mutableSets, and another for immutableSets. -
import scala.collection.mutable.HashSet val jetSet = new HashSet[String] jetSet += "Lear" jetSet += ("Boeing", "Airbus") println(jetSet.contains("Cessna"))
-
the third line initializes
jetSetwith a newHashSetthat will contain onlyStrings. Note that just as withLists andArrays, when you create aSet, you need to parameterize it with a type (in this case,String), since every object in aSetmust share the same type -
Had you wanted to, instead of writing
jetSet += "Lear", you could have writtenjetSet.+=("Lear"). Because the+=method takes a variable number of arguments, you can pass one or more objects at a time to it. -
Another useful collection class in Scala is
Maps. As withSets, Scala provides mutable and immutable versions ofMap, using a class hierarchy. -
// In treasure.scala import scala.collection.mutable.HashMap val treasureMap = new HashMap[Int, String] treasureMap += 1 -> "Go to island." treasureMap += 2 -> "Find big X on ground." treasureMap += 3 -> "Dig." println(treasureMap(2))
-
As illustrated in previous examples, the Scala compiler transforms an binary operation expression like
1 -> "Go to island."into1.->("Go to island."). -
Because maps are such a useful programming construct, Scala provides a factory method for
Maps that is similar in spirit to the factory method shown in Step 9 that allows you to createLists without using thenewkeyword. -
// In numerals.scala val romanNumeral = Map(1 -> "I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V") println(romanNumeral(4))
-
In
numerals.scalayou take advantage of the fact that the the immutableMaptrait is automatically imported into any Scala source file. -
class SimpleGreeter { val greeting = "Hello, world!" def greet() = println(greeting) } val g = new SimpleGreeter g.greet()
-
One difference between Java and Scala involves constructors. In Java, classes have constructors, which can take parameters, whereas in Scala, classes can take parameters directly. The Scala notation is more concise—class parameters can be used directly in the body of the class; there’s no need to define fields and write assignments that copy constructor parameters into fields
-
class FancyGreeter(greeting: String) { def greet() = println(greeting) } val g = new FancyGreeter("Salutations, world") g.greet
-
Instead of defining a constructor that takes a
String, as you would do in Java, ingreetFancily.scalayou placed thegreetingparameter of that constructor in parentheses placed directly after the name of the class itself -
When defined in this way,
greetingessentially becomes a value (not a variable—it can't be reassigned) field that's available anywhere inside the body. -
Fortunately, you can. Any code sitting inside the curly braces surrounding the class definition, but which isn't part of a method definition, is compiled into the body of the primary constructor. In essence, the primary constructor will first initialize what is essentially a final field for each parameter in parentheses following the class name. It will then execute any top-level code contained in the class's body.
-
class CarefulGreeter(greeting: String) { if (greeting == null) { throw new NullPointerException("greeting was null") } def greet() = println(greeting) } new CarefulGreeter(null)
-
The Scala compiler places this
ifstatement into the body of the primary constructor, just after code that initializes what is essentially a final field namedgreetingwith the passed value. Thus, if you pass innullto the primary constructor, as you do in the last line of thegreetCarefully.scalascript, the primary constructor will first initialize thegreetingfield tonull. Then, it will execute theifstatement that checks whether thegreetingfield is equal tonull, and since it is, it will throw aNullPointerException -
In Java, you sometimes give classes multiple constructors with overloaded parameter lists. You can do that in Scala as well, however you must pick one of them to be the primary constructor, and place those constructor parameters directly after the class name
-
You then place any additional auxiliary constructors in the body of the class as methods named
this. -
class RepeatGreeter(greeting: String, count: Int) { def this(greeting: String) = this(greeting, 1) def greet() = { for (i <- 1 to count) println(greeting) } } val g1 = new RepeatGreeter("Hello, world", 3) g1.greet() val g2 = new RepeatGreeter("Hi there!") g2.greet()
-
The body of this constructor consists of a single statement: an invocation of the primary constructor parameterized with the passed
greetingand a count of 1 -
Another area in which Scala departs from Java is that you can't have any static fields or methods in a Scala class. Instead, Scala allows you to create singleton objects using the keyword
object. A singleton object cannot, and need not, be instantiated withnew. It is essentially automatically instantiated the first time it is used, and as the “singleton” in its name implies, there is ever only one instance. A singleton object can share the same name with a class, and when it does, the singleton is called the class's companion object. The Scala compiler transforms the fields and methods of a singleton object to static fields and methods of the resulting binary Java class. -
class WorldlyGreeter(greeting: String) { def greet() = { val worldlyGreeting = WorldlyGreeter.worldify(greeting) println(worldlyGreeting) } } // The WorldlyGreeter companion object object WorldlyGreeter { def worldify(s: String) = s + ", world!" }
-
In fact, when the Scala compiler generates bytecodes for this file, it will create a Java class named
WorldlyGreeterthat has an instance method namedgreet(defined in theWorldlyGreeterclass in the Scala source) and a static method namedworldify(defined in theWorldlyGreetercompanion object in Scala source). -
you invoke the singleton object's
worldifymethod using a syntax similar to the way you invoke static methods in Java: the singleton object name, a dot, and the method name: -
val worldlyGreeting = WorldlyGreeter.worldify(greeting)
-
-
11 Sep 14
-
It has the conciseness of a dynamic language like Ruby or Python, but it is statically typed, like Java. Another reason is that Scala comes with an Erlang-like Actors library that greatly simplifies concurrent programming, but runs on the JVM
-
-
11 Aug 14
-
23 Feb 14
-
object-oriented programming language that blends imperative and functional programming styles.
-
The main Scala compiler,
scalac, generates Java class files that can be run on the JVM. -
Scala language can be used alongside the Java language
-
it allows you to increase your productivity compared to Java while leveraging JVM execution speed,
-
has the conciseness of a dynamic language like Ruby or Python, but it is statically typed, like Java.
-
Actors library that greatly simplifies concurrent programming,
-
vals, variables that are assigned once and never change, -
type inference.
-
Method definitions start with
definstead ofvalorvar. -
you must always explicitly specify a method's parameter types regardless of whether you explicitly specify its result type.
-
you'll likely often find yourself programming in a more functional style. I
-
unctions are first class constructs,
-
Scala achieves a conceptual simplicity by treating everything, from arrays to expressions, as objects with methods.
-
ons prepends a new element to the beginning of an existing
List,
-
-
20 Feb 14
-
In contrast to Java, where you specify a variable&8217;s type before its name, in Scala you specify a variable's type after its name, separated by a colon.
-
What you can't do with
msg, given that it is avalnot avar, -
scala> def max(x: Int, y: Int): Int = if (x < y) y else x
-
def max2(x: Int, y: Int) = if (x < y) y else x
-
def max3(x: Int, y: Int) = { if (x < y) y else x }
-
as in Java, you must put the boolean expression for a
whileor anifin parentheses. (In other words, you can't say in Scala things likeif i < 10as you can in a language such as Ruby. -
If an anonymous function consists of one method application that takes a single argument, you need not explicitly name and specify the argument.
-
for (arg <- args) println(arg)
-
When you define a variable with
val, the variable can't be reassigned, but the object to which it refers could potentially still be mutated -
val oneTwoThreeFour = oneTwo ::: threeFour
-
the most common operator you'll use with
Lists is::, which is pronounced “cons.” Cons prepends a new element to the beginning of an existingList, and returns the resultingList. -
val oneTwoThree = 1 :: 2 :: 3 :: Nil
-
Like
Lists, tuples are immutable, but unlikeLists, tuples can contain different types of elements -
println(pair._1) println(pair._2)
-
in Scala, classes can take parameters directly.
-
Another area in which Scala departs from Java is that you can't have any static fields or methods in a Scala class. Instead, Scala allows you to create singleton objects using the keyword
object. -
this singleton object is not a companion object. It is instead called a stand-alone. object
-
Scala includes a construct called a trait, which is similar in spirit to Java's
interface
-
-
01 Feb 14
-
04 Oct 13
-
14 Aug 13
-
he first line of code in this for comprehension illustrates another general rule of Scala: if a method takes only one parameter, you can call it without a dot or parentheses.
tois actually a method that takes oneIntargument. The code0 to 2is transformed into the method call0.to(2). (Thistomethod actually returns not anArraybut a Scala iterator that returns the values 0, 1, and 2.) Scala doesn't technically have operator overloading, because it doesn't actually have operators in the traditional sense. Characters such as+,-,*, and/, have no special meaning in Scala, but they can be used in method names. Thus, the expression1 + 2, which was the first Scala code you typed into the interpreter in Step 1, is essential in meaning to1.+(2), where+is the name of a method defined in classscala.Int. -
Similarly, when an assignment is made to a variable that is followed by some arguments in parentheses, the compiler will transform that into an invocation of an
updatemethod that takes two parameters. For example,greetStrings(0) = "Hello"
will essentially be transformed into
greetStrings.update(0, "Hello")
-
-
04 Aug 13
-
09 Apr 13
-
04 Nov 12
-
03 Oct 12
-
27 May 12
-
27 Mar 12
-
14 Mar 12
carlos puentesScala is a statically typed, object-oriented programming language that blends imperative and functional programming styles. Scala is designed to integrate easily with applications that run on modern virtual machines, primarily the Java virtual machine (JVM). The main Scala compiler, scalac, generates Java class files that can be run on the JVM. However, another Scala compiler exists that generates binaries that can be run on the .NET CLR, as Scala is designed to integrate with both the Java and .NET worlds. In the Java world, the Scala language can be used alongside the Java language—either as an alternative to Java—to build applications that run on the JVM.
scala tutorial programming java introduction language languages functional
-
17 Feb 12
-
31 Jan 12
-
06 Dec 11
-
07 Nov 11
-
10 Oct 11
-
04 Oct 11
-
16 Sep 11
-
04 Sep 11
-
26 Aug 11
-
25 Aug 11
-
scala> println("Hello, world!") Hello, world! unnamed2: Unit = ()
-
The type of the result here is
scala.Unit, which is Scala's analogue tovoidin Java. The main difference between Scala'sUnitand Java'svoidis that Scala lets you write down a value of typeUnit, namely(), whereas in Java there is no value of typevoid. (In other words, just as1,2, and3, are potential values of typeintin both Scala and Java,()is the one and only value of typeUnitin Scala. By contrast, there are no values of typevoidin Java.) Except for this,Unitandvoidare equivalent. -
The recommended style guideline for such method invocations is that if the method may have side effects4, you should provide the parentheses even if the compiler doesn't require them. Thus in this case, since the
greetmethod prints to the standard output, it has side effects and you should invoke it with parentheses to alert programmers looking at the code.
-
-
05 Aug 11
-
29 Jul 11
-
25 Jul 11
-
08 Jul 11
-
04 Jul 11
-
-
More generally, all of Java's primitive types are defined as aliases for classes in the
scalapackage. For example, if you typebooleanin a Scala program, the type you'll actually get isscala.Boolean. Or if you typefloat, you'll getscala.Float. -
scala.Unit, which is Scala's analogue tovoidin Java -
1,2, and3, are potential values of typeintin both Scala and Java,()is the one and only value of typeUnitin Scala. By contrast, there are no values of typevoidin Java. -
Sometimes the Scala compiler will require you to specify the result type of a method. If the method is recursive1, for example, you must explicitly specify the method result type.
-
indented two spaces, the recommended indentation style for Scala
-
// In greetFancily.scala class FancyGreeter(greeting: String) { def greet() = println(greeting) } val g = new FancyGreeter("Salutations, world") g.greetInstead of defining a constructor that takes a
String, as you would do in Java, ingreetFancily.scalayou placed thegreetingparameter of that constructor in parentheses placed directly after the name of the class itself, before the open curly brace of the body of classFancyGreeter. When defined in this way,greetingessentially becomes a value (not a variable—it can't be reassigned) field that's available anywhere inside the body. -
Any code sitting inside the curly braces surrounding the class definition, but which isn't part of a method definition, is compiled into the body of the primary constructor. In essence, the primary constructor will first initialize what is essentially a final field for each parameter in parentheses following the class name. It will then execute any top-level code contained in the class's body.
-
Thus, a singleton object is either a companion or a stand-alone object. The distinction is important because companion objects get a few special privileges, such as access to private members of the like-named class.
-
Note that one difference with Java is that to override a method in Scala, you must precede the method's
defwithoverride
-
-
01 Jul 11
-
20 Jun 11
-
17 Jun 11
-
31 May 11
-
23 May 11
-
10 Mar 11
-
15 Jan 11
-
03 Jan 11
-
25 Dec 10
-
23 Dec 10
-
06 Dec 10
-
01 Dec 10
-
30 Nov 10
-
statically typed, object-oriented programming language that blends imperative and functional programming styles.
-
integrate with both the Java and .NET worlds.
-
developed starting in 2003 by Martin Odersky's group at EPFL, Lausanne, Switzerland.
-
He co-designed the first version of Java generics and was the original author of the current
javaccompiler. -
increase your productivity compared to Java
-
vast array of APIs available for the JVM.
-
In Italian, Scala means staircase
-
examples in this article were run with Scala version 2.5.0-RC1, so make sure you download a version at least as recent as 2.5.0-RC1.
-
add the full pathname of the
bindirectory to yourPATH -
other requirement you'll need to fulfill is an installation of Java 1.4 or above
-
vals, variables that are assigned once and never change, andvars, variables that may change over their lifetime. -
If reassignment is what you want, you'll need to use a
var, as in: -
Method definitions start with
def -
write some methods.
-
always explicitly specify a method's parameter types
-
scala> def greet() = println("Hello, world!") greet: ()UnitYou can call it with or without parentheses:
scala> greet() Hello, world! unnamed7: Unit = () scala> greet Hello, world! unnamed8: Unit = ()
-
println("Hello, world, from a script!")then run:
>scala hello.scala
-
// Say hello to the first argument println("Hello, " + args(0) + "!")then run:
>scala helloarg.scala planet
-
can run a Scala script as a shell script
-
The initial
#!/bin/shmust be the very first line in the file. Once you set its execute permission:>chmod +x helloarg
-
var i = 0 while (i < args.length) { println(args(i)) i += 1 }
-
ou must put the boolean expression for a
whileor anifin parentheses -
Scala gives you the conciseness of a scripting language such as Ruby or Python, but without requiring you to give up the static type checking of more verbose languages like Java or C++.
-
support for the functional programming style
-
args.foreach(arg => println(arg))
-
scala pa.scala Concise is nice
You should see:
Concise is nice
-
args.foreach((arg: String) => println(arg))
-
addition to being functional, Scala is object-oriented.
-
val s = new String("Hello, world!") println(s)
-
val greetStrings = new Array[String](3) greetStrings(0) = "Hello" greetStrings(1) = ", " greetStrings(2) = "world! " for (i <- 0 to 2) print(greetStrings(i))
-
val greetStrings: Array[String] = new Array[String](3)
-
index inside parentheses, not square
-
greetStrings(0) = "Hello" greetStrings(1) = ", " greetStrings(2) = "world! "
-
tois actually a method that takes oneInt -
variable can't be reassigned, but the object to which it refers could potentially still be mutated.
-
define a variable with
val, -
Arrays are simply instances of classe
-
a method named
apply. -
any type into an apply method call, n
-
, the compiler will transform that into an invocation of an
updatemethod that takes two parameters. For example, -
you insight into why arrays are accessed with parentheses in Scala.
-
hat methods should not have side effects
-
method should be to compute the value or values that are returned by the method.
-
To apply this functional philosophy to the world of objects, you would make objects immutable.
-
Scala
Arrayis a mutable sequence of objects that all share the same type. -
val oneTwoThree = List(1, 2, 3)
-
most common operator you'll use with
Lists is::, which is pronounced “cons.” -
val twoThree = List(2, 3) val oneTwoThree = 1 :: twoThree println(oneTwoThree)
And execute it with
scala consit.scala, you should see:List(1, 2, 3)
-
For example, if you type the following code into a file named
consinit.scala:val oneTwoThree = 1 :: 2 :: 3 :: Nil println(oneTwoThree)
-
n Scala is the tuple. Like
Lists, tuples are immutable, but unlikeLists, tuples can contain different types of elements. -
ordered collection of object e
-
Scala infers the type of the tuple to be
Tuple2[Int, String], and gives that type to the variablepairas well. In the second line, you access the_1field, which will pro -
Scala aims to help you take advantage of both functional and imperative styles, its collections libraries make a point to differentiate between mutable and immutable collection classes.
-
the Scala API contains a base trait for
Sets, where a trait is similar to a Javainterface -
Scala then provides two subtraits, one for mutable
Sets, and another for immutableSets. -
To try out Scala
Sets, type the following code into a file namedjetset.scala:import scala.collection.mutable.HashSet val jetSet = new HashSet[String] jetSet += "Lear" jetSet += ("Boeing", "Airbus") println(jetSet.contains("Cessna")) -
Scala provides mutable and immutable versions of
Map, using a class hierarchy. As you can see in Figure 3, the class hierarchy forMaps looks a lot like the one forSets. There's a baseMaptrait in packages -
Another useful collection class in Scala is
Maps. -
Implementations of
Map, such as theHashMaps shown in the class hierarchy in Figure 3, implement either the mutable or immutable trait. -
val treasureMap = new HashMap[Int, String] treasureMap += 1 -> "Go to island." treasureMap += 2 -> "Find big X on ground." treasureMap += 3 -> "Dig." println(treasureMap(2))
On the first line of
treasure.scala, you import the mutable form ofHashMap -
type the following code into a file called
numerals.scala:// In numerals.scala val romanNumeral = Map(1 -> "I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V") println(romanNumeral(4))
-
The Scala notation is more concise—class parameters can be used directly in the body of the class; there’s no need to define fields and write assignments that copy constructor parameters into fields. This can yield substantial savings in boilerplate code; especially for small classes. To see this in action, type the following code into a file named
greetFancily.scala: -
construct called a trait, which is similar in spirit to Java's
interface. One main difference between Javainterfaces and Scala's traits are that whereas all methods in Javainterfaces are by definition abstract, you can give methods real bodies with real code in Scala traits. Here's an example: -
get more productivity while leveraging existing investments.
-
productivity compared to the Java langauge
-
-
17 Nov 10
-
18 Oct 10
-
06 Oct 10
-
03 Oct 10
-
02 Oct 10
-
17 Sep 10
-
30 Jul 10
-
10 Jul 10
-
Another area in which Scala departs from Java is that you can't have any static fields or methods in a Scala class. Instead, Scala allows you to create singleton objects using the keyword
object. A singleton object cannot, and need not, be instantiated withnew. It is essentially automatically instantiated the first time it is used, and as the “singleton” in its name implies, there is ever only one instance. A singleton object can share the same name with a class, and when it does, the singleton is called the class's companion object. The Scala compiler transforms the fields and methods of a singleton object to static fields and methods of the resulting binary Java class.
-
-
06 Jul 10
-
17 Jun 10
-
13 May 10
-
10 May 10
-
08 May 10
-
17 Feb 10
-
03 Feb 10
-
22 Jan 10
Danilo BarsottiTutorial que faz um getting started no scala, muito interessante e com um excelente conteudo.
-
20 Jan 10
-
02 Jan 10
-
20 Dec 09
-
20 Nov 09
-
05 Nov 09
-
01 Nov 09
-
Scalazine
First Steps to Scala
by Bill Venners, Martin Odersky, and Lex Spoon
-
-
17 Oct 09
-
07 Oct 09
-
01 Oct 09
-
27 Sep 09
-
15 Sep 09
-
14 Sep 09
-
10 Sep 09
-
15 Aug 09
-
10 Aug 09
-
24 Jul 09
-
16 Jul 09
-
21 Jun 09
-
05 Jun 09
-
24 Apr 09
-
08 Apr 09
-
06 Apr 09
-
Francois ZaninottoScala is a statically typed, object-oriented programming language that blends imperative and functional programming styles. Scala is designed to integrate easily with applications that run on modern virtual machines, primarily the Java virtual machine (JV
-
05 Apr 09
-
02 Apr 09
-
26 Mar 09
-
23 Mar 09
-
22 Mar 09
-
18 Mar 09
-
14 Mar 09
-
06 Mar 09
-
04 Mar 09
-
15 Nov 08
Would you like to comment?
Join Diigo for a free account, or sign in if you are already a member.