Scala basic Syntax __scala

Source: Internet
Author: User
Tags instance method traits
An expression
Scala> 1 + 1
res0:int = 2

value

You can assign the result of an expression to a variable (val) by name.

scala> val two = 1 + 1
two:int = 2

variable

If you need to modify the binding of this name and result, you can choose to use Var.

scala> var name = "Steve"
name:java.lang.String = Steve

scala> name = "Marius"
name:java.lang.String = Marius

function

You can use DEF to create a function.

Scala> def addone (m:int): int = m + 1
addone: (m:int) int

In Scala, you need to specify a type signature for the function argument.

scala> val three = AddOne (2)
Three:int = 3

If the function takes no arguments, you can not write parentheses.

Scala> def three () = 1 + 2
Three: () Int

scala> Three ()
res2:int = 3

scala> three res3
: Int = 3

Anonymous Functions

You can create anonymous functions.

Scala> (X:int) => x + 1
res2: (int) => Int = <function1>

This function is an int variable named x plus 1.

Scala> res2 (1)
Res3:int = 2

You can pass anonymous functions, or save them as invariants.

scala> val addone = (x:int) => x + 1
addone: (int) => Int = <function1>

scala> addone (1)
re S4:int = 2

If your function has many expressions, you can use {} to format the code so that it is readable.

def timestwo (i:int): Int = {
  println ("Hello World")
  I * 2
}

The same is true for anonymous functions.

scala> {i:int =>
  println ("Hello World")
  I * 2
}
res0: (int) => Int = <function1>

This syntax is often used when passing an anonymous function as a parameter. Partial applications (Partial application)

You can use the underscore "_" section to apply a function, and the result will be another function. Scala uses underscores to represent different things in different contexts, and you can usually think of it as a magic wildcard without a name. In the context of {_ + 2}, it represents an anonymous parameter. You can use it this way:

Scala> def adder (m:int, n:int) = m + N
adder: (m:int,n:int) Int

scala> val add2 = Adder (2, _:int)
add 2: (int) => Int = <function1>

scala> add2 (3)
Res50:int = 5


You can partially apply any of the parameters in the parameter list, not just the last one. The function of the Gerty

Sometimes there is a need to allow someone to apply some parameters to your function and then apply some additional parameters.

For example, a multiplication function needs to select the multiplier in one scene and the other to select the multiplier.

scala> def multiply (m:int) (n:int): int = m * N
Multiply: (m:int) (n:int) int

You can pass in two parameters directly.

Scala> Multiply (2) (3)
Res0:int = 6

You can fill in the first argument and partially apply the second parameter.

scala> val timestwo = Multiply (2) _
timestwo: (int) => Int = <function1>

scala> timestwo (3)
re S1:int = 6

You can perform a curry on any of the multiple parameter functions. For example, the previous Adder function

The first argument is a addends, returns a function, calls the second function, and the other number, and the result is

Scala> (Adder _). Curried
res1: (int) => (int) => int = <function1>

scala> res1 (2)
Res2: (In T) => Int = <function1>

scala> res2 (3)
Res3:int = 5

variable length parameters

This is a special syntax that allows you to pass any number of parameters of the same type to a method. For example, to execute a string's capitalize function on multiple strings, you can write this:

def capitalizeall (args:string*) = {
  Args.map {arg =>
    arg.capitalize
  }
}

scala> Capitalizeall ("Rarity", "Applejack")
res2:seq[string] = Arraybuffer (rarity, Applejack)

class

Scala> class Calculator {
     |   Val brand:string = "HP"
     |   def add (M:int, n:int): Int = m + N
     |}
Defined class Calculator

scala> val calc = new Calculator
calc:calculator = calculator@e75a11 scala>

C Alc.add (1, 2)
res1:int = 3

scala> calc.brand
res2:string = "HP"

The above example shows how to define a method in a class with Def and define field values with Val. A method is a function that can access the state of a class. Constructors

Constructors are not special methods, they are code other than the method definition of a class. Let's expand the calculator example, add a constructor parameter, and use it to initialize the internal state.

Class Calculator (brand:string) {
  /**
   * A constructor.
   * *
  val color:string = if (brand = = "TI") {
    "blue"
  } else if (brand = "HP") {
    "black"
  } else {
   "White"
  }

  //A instance method.
  def add (M:int, n:int): Int = m + N
}

Pay attention to two different styles of comment.

You can use constructors to construct an instance:

scala> val calc = new Calculator ("HP")
calc:calculator = calculator@1e64cc4d

scala> calc.color
: String = Black

An expression

The calculator example above illustrates how Scala is oriented to expression. The value of a color is bound to a if/else expression. Scala is highly expression-oriented: most things are expressions, not directives. Narrator: Function vs Method

Functions and methods are, to a large extent, interchangeable. Because functions and methods are so similar, you may not know what you are calling a function or a method. And when the difference between the method and the function is actually encountered, you may be confused.

Scala> class C {
     |   var acc = 0
     |   def minc = {acc = 1}
     |   Val finc = {() => ACC + + 1}
     |}
Defined Class C

scala> val c = new C
c:c = C@1af1bd6

scala> c.minc//Calls C.minc ()

scala> C.finc//Returns the function as a value:
res2: () => unit = <function0>

When you can call a "function" without parentheses, but you have to add parentheses to the other, you might think, gee, I thought I knew how Scala works. Maybe they sometimes need braces. You might think you're using a function, but you're actually using a method.

In practice, you can do great things with Scala, even if you don't understand the difference between methods and functions. If you're a beginner in Scala and you're reading the difference between the two, you might not be able to keep up. But that doesn't mean you're having trouble using Scala. It simply means that the difference between the function and the method is subtle, and it can be clearly understood only in the depth of the language. inherited

Class Scientificcalculator (brand:string) extends Calculator (brand) {
  def log (m:double, base:double) = Math.log (m)/ Math.log (base)
}

Reference Effective Scala points out that the type alias is superior to inheritance if the fruit class is virtually indistinguishable from the parent class. A Tour of Scala introduces subclasses in detail. Overloaded Methods

Class Evenmorescientificcalculator (brand:string) extends Scientificcalculator (brand) {
  def log (m:int): Double = Log (M, Math.exp (1))
}

Abstract class

You can define an abstract class that defines some methods but does not implement them. Instead, these methods are defined by the subclass of the extended abstract class. You cannot create an instance of an abstract class.

Scala> abstract class Shape {
     |   Def getarea (): Int    //subclass should define this
     |}
Defined class Shape

scala> class Circle (r:int) extends Shape {
     |   Def getarea (): Int = {R * R * 3}
     |}
Defined class Circle

scala> val s = new shape
<console>:8:error:class shape is abstract; cannot Stantiated
       val s = new Shape
               ^

scala> val c = new Circle (2)
c:circle = circle@65c0035b

trait (Traits)

A trait is a collection of fields and behaviors that can be extended or mixed into (mixin) your class.

Trait car {
  val brand:string
}

trait shiny {
  val shinerefraction:int
}

class BMW extends Car {
  val brand = "BMW"
}


With the WITH keyword, a class can extend multiple attributes:

Class BMW extends car with shiny {
  Val brand = "BMW"
  val shinerefraction =

Reference Effective Scala's view of the trait.

when you should use attributes rather than abstract classes. if you want to define a type that resembles an interface, you may find it difficult to choose between the trait and the abstract class. Both of these forms allow you to define some behavior of a type and require the successor to define some other behavior. Some rule of thumb: Prioritize the use of traits. It is convenient for a class to extend multiple attributes, but only an abstract class can be extended.
If you need constructor parameters, use an abstract class. Because an abstract class can define a constructor with parameters, the attribute is not. For example, you cannot say trait T (i:int) {}, parameter I is illegal.

You are not the first person to ask this question. You can see a more comprehensive answer: the Stackoverflow:scala trait vs. abstract class, abstract class and trait differences, and Scala programming: using traits, or not. type

Previously, we defined a function with an int, which means that the input is a numeric type. In fact, the function can also be generic, to apply to all types. When this happens, you will see the type parameters introduced with the square brackets syntax. The following example shows a cache that uses a generic key and a value.

Trait Cache[k, V] {
  def get (key:k): V
  def put (Key:k, value:v)
  def delete (key:k)
}

Method can also introduce type parameters.

def Remove[k] (key:k)

=============================================================================================================== ========================================================

Apply Method

When a class or object has a primary purpose, the Apply method provides you with a good syntax for sugar.

Scala> class Foo {}
defined class Foo

scala> object Foomaker {
     |   def apply () = new Foo
     |}
Defined module Foomaker

scala> val newfoo = Foomaker ()
Newfoo:foo = foo@5b83f762

Or

Scala> class Bar {
     |   def apply () = 0
     |}
Defined class Bar

scala> val bar = new Bar
Bar:bar = bar@47711479

scala> bar ()
res8:int = 0

Here, we instantiate the object as if it were calling a method. There will be more introductions in the future. Single Case Object

A singleton object is used to hold a unique instance of a class. Typically used in Factory mode.

Object Timer {
  var count = 0

  def currentcount (): Long = {
    count + = 1
    count
  }
}

You can use this:

Scala> timer.currentcount ()
Res0:long = 1

A single Instance object can have the same name as a class, and the object is also referred to as the companion object. We usually use the companion object as a factory.

Here's a simple example where you don't need to use ' new ' to create an instance. Apply

Class Bar (foo:string)

Object Bar {
  def apply (foo:string) = new Bar (foo)
}

A function is an object

In Scala, we often talk about functional programming of objects. What does that mean. What exactly is a function?

A function is a collection of attributes. In particular, a function with one parameter is an example of a Function1 trait. This feature defines the apply () syntax sugar, which allows you to call an object as if you were calling a function.

Scala> Object AddOne extends Function1[int, Int] {
     |   def apply (m:int): Int = m + 1
     |}
Defined module AddOne

scala> addone (1)
Res2:int = 2

This function trait set subscript starting from 0 to 22. Why is 22. This is a subjective magic figure (magic number). I've never used a function with more than 22 parameters, so this number seems reasonable.

Apply syntax sugar helps unify objects and functional programming in duality. You can pass classes and use them as functions, and functions are essentially instances of classes.

Does this mean that when you define a method in a class, it is actually a function* instance. No, the method defined in the class is a method, not a function. The method that is defined independently in REPL is an instance of function*.

Classes can also extend function, and instances of these classes can be invoked using ().

Scala> class AddOne extends Function1[int, Int] {
     |   def apply (m:int): Int = m + 1
     |}
Defined class AddOne

scala> val plusone = new AddOne ()
plusone:addone = <function1>

scala> pluso NE (1)
Res0:int = 2

You can use a more intuitive and quick extends (int => int) instead of extends Function1[int, int]

Class AddOne extends (int => int) {
  def apply (m:int): Int = m + 1
}

Package

You can organize your code into a package.

Package Com.twitter.example

Defining a package in the header of a file will declare all the code in the file in that package.

Values and functions cannot be defined outside of a class or a single instance object. A single Instance object is an effective tool for organizing static functions.

Package Com.twitter.example

Object Colorholder {
  val blue = "BLUE"
  val red = "Red"
}

Now you can access these members directly

println ("The color is:" + Com.twitter.example.colorHolder.BLUE)

Notice the return of the Scala interpreter when you define this object:

Scala> object Colorholder {
     |   Val blue = "Blue"
     |   Val red = "Red"
     |}
Defined module Colorholder

This implies that Scala's designers are designing objects as part of a Scala modular system. Pattern Matching

This is one of the most useful parts of Scala.

Match value

Val times = 1 times

Match {case
  1 => "one"
  

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.