Scala Foundation 02: Functions, exceptions

Source: Internet
Author: User

Default parameters for functions

Cases:

def decorate (str:string, left:string = "[", right:string = "]") = left + str + right

A call to an parameterless function may not use parentheses. However, the default parameters do not represent no parameters. For a function where all parameters are default arguments, the call must use parentheses.

Cases:

def hellospark (name:string = "Spark") {

println (name)

}

Call this function:

Hellospark Error

Hellospark () correct

Hellospark ("Java")

function with Name parameter

Cases:

def sum (x:int, y:int) = {

X + y

}

Call sum

val s = sum (y =, x = 82))

Variable-length parameters for functions

Cases:

def sum (args:int*) = {

var result = 0

for (Arg <-args) result +=arg

Result

}

def printeachstr (args:string*) = {

Args.foreach (args = println (x))

}

Lazy value

When a lazy value is defined, the value is not computed and is actually assigned when the value is used.

A lazy value is used in a situation where the calculation of values is very complex or computationally expensive.

Cases:

Lazy val words = Scala.io.Source.fromFile ("/usr/share/dict/words"). mkstring

If the program never accesses words, then the file will not be opened.

Exception Handling (throw/try)

Scala handles exceptions by throwing an exception and aborting it, either catching and handling the exception, or simply aborting it.

Exception throw: throw new IllegalArgumentException

Exception capture and Processing: try{function Body} catch{case ... Case ...}

Catch uses pattern matching to handle different exceptions.

Exception capture and Abort: try{function Body} finally{a.close ()}

try-catch-finally-expression

try{function Body} catch{case ...; Case ...} Finally{a.close ()}

A throw, try-catch-finally expression can generate a value.

Such as: throw new IllegalArgumentException ("error!")

def f (): Int=try{1} finally{2}

Example: throws an exception.

Val n = 99

Val half = if (n%2 = = 0) n/2 Else throw new RuntimeException ("N Must be Event")

Example: Catching an exception

Val n = 99

try {

Val half = if (n%2 = = 0) n/2 Else throw new RuntimeException ("N Must be Event")

} catch {

Case e:exception = println ("The Exception is:" + e.getmessage)

}

Scala array

Fixed-length arrays

Declares the basic format of an array:

Val arr = new Array[t] (N)

Cases:

Val nums = new Array[int] (10)

Val STRs = new Array[string] (10)

When an array declaration is not given a value, it is initialized and can be assigned to the member of the group after initialization.

Array member initialization, such as type int, is initialized to NULL for the 0,string type.

Assigning a value directly to an array

Basic format:

Val arr = Array (x1,x2,.... xn);

Cases:

val s = Array ("Hello", "World")

Accessing array elements

Use () instead of [] to access the element.

Assigning a value to an array element

S (1) = "Scala"

Variable-length arrays

Using variable-length arrays requires the introduction of packages:

Import Scala.collection.mutable.ArrayBuffer

Declares an empty array cache, at which point B is an all-empty array with an array length of 0.

Val B = Arraybuffer[int] ()

Adds an element "1" to the tail of the array.

B+=1

Adds a series of elements "2,3" at the end of the array.

b+= (2,3)

Adds an array of elements (5,8,13,21) to the tail of the B array.

B++=array (5,8,13,21)

Removing the last 3 elements

B.trimend (3)

Inserts an element before the element with the mark bit 2.

B.insert (2,-2)

Inserts a series of elements before the element that marks bit 2.

B.insert (2,-3,-5)

Removes an element with a mark bit of 3.

B.remove (3)

Removes 2 elements by removing the element with the mark bit 1 and beyond.

B.remove (ON)

Converts the variable-length array to a fixed-length array.

Val C = B.toarray

Convert a fixed-length array to a variable-length array

Val d = C.tobuffer

Iterating through an array

Iterate by array ordinal.

for (i <-0 until a.length) {

println (i+ ":" +a (i))

}

Iterate directly over the members of the array (this is a better practice)

For (i <-array) {

println (i)

}

Get members by iterating over the array's subscript

for (i <-0 to (c.length-1) {

println (C (i))

}

Traverse each of the two elements in one line

for (i <-0 to (c.length,2)) {

println (C (i))

}

Reverse traversal

For (i-<-(0 to C.length). Reverse) {

println (C (i))

}

By enumerating the array members with a For statement, you can implement a variety of array controls, such as adding 1 to the array members and generating a new array:

Val new=for (i <-C) yield i+1

This array generation corresponds to the original array type (fixed length/variable length)

Multidimensional arrays

Val matrix = array.ofdim[double] (3,4)//three rows, four rows

Val triangle = new Array[array[int]] (10)

for (i <-0 until Triangle.length)

Fixed-length arrays and variable-length arrays

The use of fixed-length arrays is more encouraged for Scala.

Scala Foundation 02: Functions, exceptions

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.