1. Simplicity
1.1. The Java notation
class MyClass { privateint index; Private String name; Public MyClass (int index, String name) { this. Index = index; this. Name = name; }
1.2. Scala's writing: Faster to write, easier to read, more difficult to make mistakes
Class
2. More flexible, more abstract
Suppose you have a string variable name and you want to figure out if the string contains an uppercase character.
2.1. The Java notation
Boolean false ; for (int i = 0; i < name.length (); + +i) {if (Character.isuppercase (Name.charat (i))) { true ; Break ; }
Or one step closer: interface-oriented programming
Interface characterproperty { boolean hasproperty (char ch); }
Implementing the Exists (String name, Characterproperty property) method
New characterproperty { boolean hasproperty (char ch) { return character.isuppercase (CH); }
2.2. The notation of Scala
3. Type inference
3.1
The static method of Java cannot access the type parameters of a generic class, so the static method needs to use generic capabilities and must make it a generic method.
3.2
Val x = new Hashmap[int, String] () = new HashMap ()
Or:
class Complex (real:double, imaginary:double) { def re () = Real def im () = I Maginary}
It is important to note that the return values of both methods are not explicitly defined. During compilation, the compiler can infer from the definition of a function that the return value of two functions is a double type.
Other:
def Id[t] (x:t) = XID: [T] (x:t) Tscala> val x = ID (322= 322Scala> val x = ID (
"
hey
"
=
Heyscala> val x = ID (Array (1,2,3,4
= Array (1, 2, 3, 4)
4. No Parameter method
The small problem with the RE and Im methods in the Complex class is that when you call both methods, you need to follow the method name with an empty pair of parentheses, as in the following example:
object Complexnumbers { def Main (args:array[string]) {val c= new Complex (1.2, 3.4) println ("" + c.im ())}}
If you can omit the empty parentheses after these methods, like accessing the class properties, you can access the method of the class, and the program will be more concise. This is possible in Scala.
class Complex (real:double, imaginary:double) { def re = real def im = imag Inary}
Scala Learning Notes