Scala Concise Tutorials _scala

Source: Internet
Author: User
Tags function definition traits
A concise course in Scala

Directory
Variable declaration
Function
Package Package
Data
String
Control process
Pattern matching
Object-oriented
Generic type
Annotations
Implicit
Empty Object Nil,null,null,unit,nothing,none

Scala is a multiple-paradigm (MULTI-PARADIGM) programming language.
Scala source code is compiled into Java bytecode, so it can run on top of the JVM and can invoke an existing Java class library.
Martin Odersky of the Federal Institute of Technology in Lausanne began designing Scala in 2001 based on Funnel's work. Funnel is a programming language that combines functional programming ideas with Petrelli networks. Odersky's previous work was generic Java and Javac. The Java platform Scala was released at the end of 2003/early 2004. The second version of the language, V2.0, was released in March 2006.

Scala is object-oriented, more thorough than Java

Everything is an object, a value, a function is an object
All support functional programming
Including functions are objects, lambda,currying, type inference, immutability, lazy evaluation, and pattern matching
A powerful static type system
Algebraic data types, covariance and contravariance, higher-order types, anonymous types, generic classes, upper and lower Type bounds, inner classes and abstract types as object, compound types, explicitly typed self references, views and Polymorphic methods
Other features not supported by Java:

operator overloading, optional parameters, named parameters, Raw strings, and no checked exceptions
In April 2009, Twitter announced that it had migrated most of its back-end programs from Ruby to Scala, and that the remainder was planning to migrate. Here's an article explaining why Twitter uses the Scala programming language.
Engineer-to-engineer Series Programming Languages programming Languages Scala talks
Coursera uses Scala as the server language. Why we love Scala at Coursera
Some Scala learning materials:

Scala Documentation
Learning Scala
Effective Scala
Scala School
Scala cheatsheets

Kafka and Spark in the big data biosphere are developed by Scala, which is one of the reasons why I learn Scala.
As a more than 10-year Java programmer, while learning both Scala and go languages. Learning in the process of feeling go language too studious, start quickly, and Scala's grammar and class C language such as java,c# is very different, a lot of grammar skills in it. Based on this, I have specially sorted out this article. Briefly introduce the knowledge points of Scala, especially in a different place than Java.

$ variable Declaration
var x = 5
var x:double = 5
Val y = 7 Copying code
var declares a variable, Val declares a constant, a type can be omitted, and Scala can infer the data type
Function

def f (x:int) = {X*x}
def f (x:any): unit = println (x) Copy code

Defines a function that returns a value type that can be omitted, = a block definition or an expression after an equal sign.

Reply ()
Reply Copy Code
Parentheses can be omitted when a function call without arguments.

Names foreach (n => println (n))
Names mkstring ","
Optstr getorelse "<empty>"

Copy Code
A parameter can be written using infix
The infix operator can be defined as follows:

Class Mybool (X:boolean) {
Def and (that:mybool): Mybool = if (x) that else this
def or (that:mybool): Mybool = if (x) This else is
def negate:mybool = new Mybool (!x)

def not (X:mybool) = x negate; Semicolon required Here
Def xor (X:mybool, Y:mybool) = (x or y) and not (x and Y)
}

More examples
5.+ (3); 5 + 3
(1 to 5) map (_*2)
def f (x:r)
def f (x: => R)

Copy Code
The first Call-by-value, the second call-by-name (lazy parameters)

(x:r) => x*x Copy Code

anonymous function (lambda expression)
=> can be substituted by ⇒ characters (\U21D2), and <-and-> can also be replaced by individual characters: ← and →

(1 to 5). Map (_*2)
(1 to 5). Reduceleft (_+_) Copy code

Underline represents substitution, more underline features see discussion

(1 to 5). Map (2*)
Equivalent
(1 to 5). Map (2* _)
(1 to 5). map {val x=_*2; println (x); x}
(1 to 5) filter {_%2 = = 0} map {_*2} copy code

Block style implementation of anonymous function, last statement as return value

def compose (g:r=>r, h:r=>r) = (x:r) => g (H (x))
Val F = Compose ({_*2}, {_-1}) copy Code

Multiple blocks as parameters

Val Zscore = (mean:r, sd:r) => (x:r) => (X-mean)/sd//currying, obvious syntax.
def zscore (mean:r, sd:r) = (x:r) => (X-mean)/sd//currying, obvious syntax
def zscore (Mean:r, Sd:r) (x:r) = (X-mean)/sd//currying, syntactic sugars, also called parameter groupings. However, the following syntax must be invoked:
Val Normer = Zscore (7, 0.4) _//needs a trailing underline, limited to the syntax sugar on the line above
def sum (args:int*) = Args.reduceleft (_+_) Copy code

Variable parameters
$ package Package


Import Scala.collection._//wildcard character imports, similar to java. *
Import Scala.collection.Vector
Import Scala.collection. {Vector, Sequence}//Import multiple
Import Scala.collection. {Vector => Vec28}//alias.
Import Java.util. {Date => _, _}//Except date, all other import
Package pkg at start of file
Package pkg {...} copy code

General statements can be omitted after;
& Data structure


(1,2,3)
var (x,y,z) = (1,2,3) Copy code

Tuple type

var xs = List (1,2,3)
XS (2) Copy code

List type

1:: List (2,3)
List (1, 2)::: List (2, 3)
List (1, 2) + + Set (3, 4, 3) copy code

Some special operator


1 to 5 same as 1 until 6
1 to ten by 2 copy code

Range

$ string


Val name = "James"
println (S "Hello, $name")//Hello, James
println (S "1 + 1 = ${1 + 1}") Copy code
s prefix, replacing a variable or expression in a string

Val height = 1.9d
Val name = "James"
println (f "$name%s is $height%2.2f meters tall")//James is 1.90 meters tall replication code

f prefix, printf style formatting


Scala> Raw "A\NB"
res1:string = A\NB Copy Code

Raw prefix, original character, not escaped


Scala> "a". R
Res1:scala.util.matching.Regex = a copy code

R suffix, regular expression
Implicit class Jsonhelper (private Val sc:stringcontext) extends Anyval {
def JSON (args:any*): Jsonobject = ...
}
Val X:jsonobject = json "{A: $a}" copy code

Custom String Interceptor
$ control Process

if (check) happy else sad
if (check) Happy//below
if (check) happy Else () copy code

>> If statement
while (x < 5) {println (x); x + + 1}
do {println (x); x + 1} while (x < 5) Copy code

While statement
Import Scala.util.control.breaks._
breakable {
for (x <-xs) {
if (Math.random < 0.1) break
}
}
for (x <-xs If x%2 = = 0) yield x*10//with the following equivalence
Xs.filter (_%2 = = 0). Map (_*10)
For ((x,y) <-xs Zip ys) yield x*y//equivalent to the following
(XS Zip ys) Map {case (x,y) => X*y}
for (x <-xs; y <-ys) yield x*y//with the following equivalence
XS Flatmap {x => ys map {y => x*y}}
for (x <-xs; y <-ys) {//double nested, similar to for {to {}}
println ("%d/%d =%.1f". Format (X,y, x*y))
}
for (I <-1 to 5) {
println (i)
}
for (I <-1 until 5) {
println (i)
Copy Code

$ Pattern Matching

(XS Zip ys) Map {case (x,y) => X*y}
Val v42 = 42
Some (3) match {
Case Some (' v42 ') => println ("42")
Case _ => println ("not 42")
}
Val Uppercaseval = 42
Some (3) match {
Case Some (uppercaseval) => println ("42")
Case _ => println ("not 42")
Copy Code

Case class automatically generates equals and ToString, with the same parameter = = return True
$ object-oriented
Classes that do not have an access modifier or class members default to public types.

Class C (X:R)//equivalent to
Class C (private Val x:r)
var c = new C (4) Copy Code
>> parameter is private type

Class C (Val x:r)
var c = new C (4)
c.x Copy Code

>> parameter is public type

Class C (Var x:r) {
ASSERT (x > 0, "Positive please")//constructor are class body, so you can write some statements here
var y = x//public Member
Val readonly = 5//Read Only, Cannot set
private var secret = 1//private member
def this = this (42)//other constructors
}
New{...}
Abstract class D {...}
Class C extends D {...} Inherited
Class D (Var x:r)
Class C (X:R) extends D (x)//inheritance and constructor parameters. (wishlist:automatically pass-up params by default)
Object O extends D {...} Object Definition Single Example
Trait T {...}//traits.
Class C extends T {...}//implementation interface. No constructor params. Mixin-able.
Class C extends D with T {...}
Trait T1; Trait T2//multiple traits
Class C extends T1 with T2
Class C extends D with T1 with T2
Class C extends D {override def f = ...}//must declare override
New Java.io.File ("F")//Generating class objects
List (1,2,3)
Classof[string]//class literal
X.isinstanceof[string]//Run time check
X.asinstanceof[string]//Run time cast
x:string//compile-time indicated
Final class a{
Final Val x = 1
var y = 2
}
Sealed class B Copy code

Final and sealed
For internal classes, inst1. InnerClass1 and Inst2. InnerClass1 are different types, and this is not the same as Java. If you want to use the same type, use the Class#innerclass1
$ generics


def Mapmake[t] (g:t=>t) (seq:list[t]) = Seq.map (g) Copy Code

>> method with type parameters

Class Stack[t] {
var elems:list[t] = Nil
def push (x:t) {elems = x:: Elems}
def top:t = Elems.head
def pop () {elems = Elems.tail}
Copy Code

>> class with type parameters

<p>class A
Class B extends A
def test[t: A] (t:t) = {}
Test (new A)
Test (new B)//error
Upper Type Bounds
Class A
Class B extends A
Class C extends B
def test[t: A] (t:t) = {}
Test[a] (new A)
TEST[C] (new C)//error</p> copy code >>lower Type Bounds
Class Test[+t] (x:t) Copy code >> covariant for classes
Class A
Class B extends A
Class C extends B
Class Test[t] (x:t)
Val C = new Test (new C)
Val T:test[b] = c//note:c: B, but class Test is invariant in type T. You may wish to define T as +t instead. (SLS 4.5)
Val A = new Test (new A)
Val T:test[b] = a//note:a: B, but class Test is invariant in type. You may wish to define T as-t instead. (SLS 4.5) Copy Code
>>invariant

Class Test[-t] (x:t) Copy code

>>contravariant for classes
Summarize:
1) Co-change
[+t], covariant (or "flexible") in its type parameter T, similar to the (? extends T) in Java, that is, you can replace the T with the subclass of T and T, the Richter substitution principle.
2) unchanged
Subclasses of T or parent classes are not supported, only the support T itself is known.
3) Inverter
[-T], contravariant, similar (? Supers t) can only replace T with the parent of T. Is the reverse Richter replacement principle.
4) Upper bound
Only the superclass U of T is allowed to replace T. [U: T]
5) Lower bound
Only the subclass U of T is allowed to replace T. [U;: T]
Annotations


@interface sourceURL {
Public String value ();
Public String Mail () default "";
Copy Code

Use

@interface Source {
Public String URL ();
Public String Mail ();
}

@Source (URL = "http://coders.com/",
Mail = "support@coders.com")
Class Myscalaclass ... Copy Code

Shorthand (for special properties with property name value)


@interface sourceURL {
Public String value ();
Public String Mail () default "";
}
@SourceURL ("http://coders.com/")
Class Myscalaclass ...
@SourceURL ("http://coders.com/",
Mail = "support@coders.com")
Class Myscalaclass. Copy Code

Implicit
Implicit parameters Implicit parameters
If the parameter is defined as implicit, then the parameter is automatically provided if the call is not set.
Implicit parameters are completely different from the default parameters. The default argument is that the function definition sets a default value that will be used when the caller does not specify it. Implicit arguments are different, and ultimately the caller specifies the value of the parameter, but not necessarily in the calling statement. When the compiler finds that an implicit parameter is missing, it looks for an implicit value in the program scope that conforms to the type and fails the compilation if it is not found.

Abstract class Logger {def log (s:string)}
Class FileLogger extends Logger {
def log (s:string) {println ("Log in file: + s)}"
}
Class StdoutLogger extends Logger {
def log (s:string) {println ("Stdout:" + s)}
}
def Add (A:int, B:int) (implicit Logger:logger) {
Val sum = a + b
Logger.log ("%d +%d =%d". Format (A, b, sum))
}
Implicit val log = new FileLogger
ADD (1,2)
ADD (2,3) (new StdoutLogger)//you do it explicitly copy code

If the above code does not have implicit val log = new FileLogger, there is no other logger type implicit value within the scope of the code, and the compiler will complain.
Conversely, if an implicit value of the logger type can be found, the compiler passes the implicit value as a parameter to the past.
Implicit class implicit classes
A new language construct is proposed to simplify the creation of classes which the provide.
Implicit class Richint (N:int) extends Ordered[int] {
def min (m:int): Int = if (n <= m) n Else m
...
Copy Code

is converted to
Class Richint (N:int) extends Ordered[int] {
def min (m:int): Int = if (n <= m) n Else m
...
}
Implicit final def richint (n:int): Richint = new Richint (n)

Copy Code

>> implicit method Implicit conversion
Sometimes you do not need to specify that a type is equal/Sub/More than another class, and you can disguise the association by converting the class. An event horizon specifies that a type can be "viewed as" another type. This is useful for read-only operations on objects.
Implicit functions allow types to be automatically converted. Rather, when implicit functions can help satisfy type inference, they allow for application on-demand functions. For example:

Implicit def strtoint (x:string) = X.toint
Val y:int = "123" Copy Code

>> View
View, like a type boundary, requires that a function be present for a given type. You can use <% to specify type limits, such as:

Class Container[a <% Int] {def addit (x:a) = 123 + x} copy code

This is to say that a must be "can be viewed" as Int.
Method can perform more complex type restrictions by suppressing parameters. For example, the list supports performing sum on numeric content, but not for other content. But Scala's numeric types don't all share a superclass, so we can't use T.: number. Instead, to make it work, Scala's math library defines an implied numeric[t for the appropriate type T. Then use it in the list definition:


Sum[b: A] (implicit num:numeric[b]): B Copy Code

If you call list (1,2). SUM (), you don't need to pass in a num parameter; it is implicitly set. But if you call list ("Whoop"). SUM (), it complains that Num cannot be set.
The method may require a particular type of "evidence" when no unfamiliar object is set to numeric. The following type-relational operators can be used:
| | |
|---|---|
| A =:= B | A must be equal to B |
| A <:< B | A must be a subclass of B |
| A <%< B | A must be seen as a b|.


Class Container[a] (value:a) {def addit (implicit evidence:a =:= Int) = 123 + value} copy code

$ empty Object Nil,null,null,unit,nothing,none

1 Nothing is trait, defined as: final trait nothing extends any. Nothing is at the bottom of the Scala type system and is a subtype of all types, none of which has an instance.
2 NULL is trait, defined as: final trait Null extends Anyref. Null is a subtype of all reference types, and only one instance is null.
3 NULL is an instance of NULL, similar to NULL in Java
4) Nil is case object, which is defined as an object Nil extends List[nothing], representing an empty List with a length of 0. Because the list in Scala is covariant, nil is an instance of list[t, regardless of the type of T.
5 None is case object, which is defined as: Object none extends Option[nothing], which represents a nonexistent value. option has two instances. None and some

6 unit is class, defined as: Abstract final class unit extends Anyval. The unit is equivalent to void in Java, and when a method does not return any value, the type of the method is unit. The only instance of the Unit is ().


From:http://www.aboutyun.com/thread-12224-1-1.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.