Scala language study notes - method, function and abnormal

1.Scala method and difference functions
 ① Scala method has a function, semantic difference between the two is small. Scala method is part of the class, and is a function of the object can be assigned to a variable. In other words, the function that is defined in the class method

 Similar methods ② Scala with Java, the method is part of the composition of the class

 The function ③ Scala is a complete object, function Scala in fact, inherited the class of the object Trait

 ④ Scala val statement using defined functions, def statement defines the methods and functions

{the Test class
DEF Method (X: Int). 3 + X =
Val = function (X: Int). 3 = X +>
}
2.Scala method
declaration syntax method ①

   The basic syntax

      def method name ([Parameter name: Parameter Type], ...) [[: Return Value Type] =] {

          Statement ...

          return return value

     }

    Definitions: [] denotes Alternatively, there may, or may not, if not write = {}, and the number is equal to the method body, then the method is implicitly declared abstract (abstract), comprising also his type is an abstract Types of

    1) method declaration keyword def (definition)

    2) [Parameter name: Parameter Type], ...: that function's parameter list, you can not. If there are a plurality of parameters separated by commas

    3) The method of statement: that in order to achieve a certain function block

    4) The method can return a value may not

    5) returns the value 1 in the form:: Return Value Type =  

getRes DEF (N1: Int, N2: Int, Oper: Char): Int = {
N1 + N2
}
    . 6) Return value form 2: Return Value Type = represents uncertainty, using type inference complete

def getRes (n1: Int, n2 : Int, oper: Char): Int = {// the return value of the method declaration: Int
IF (Oper == '+') {
N1 + N2
} the else IF (Oper == ' - ') {
N1 - n2
} the else {
null // run error
}
}
    Note: because null is a subclass of AnyRef, but null is not a subclass of AnyVal, here the compiler does not complain, but the run will be reported typeError exception if non to return null, then the method may return value: Int removed directly = number, type inference Scala will be returned automatically

    7) returns the value in the form of 3: that there is no return value, return does not take effect

getRes DEF (N1: Int, N2: Int, Oper: Char) {
return N1 + N2 // code to run normally, but does not take effect return
}
    8) If there is no return, to perform default to the last row of the result as a return value

② method Notes

 1) a list of parameter may be a plurality of methods, if the method is not formal parameters, and may not be invoked with ()

 2) a list of parameter values ​​and returns a list of the data types can be a value type and reference type

 3) A method in Scala can return type estimation method according to the last line of code method body itself. So in this case, return keyword can be omitted

 4) Since Scala can infer its own, so that in the case return keyword is omitted, the type of the return value may be omitted

 5) If the method explicitly use the return keyword, then the method returns the inference can not be used on their own, this time to clearly written as: return type =, of course, if you do not write anything, even with the return value return ()

def getSum (n1: Int, n2 : Int) = {// = number can not be omitted, and if omitted, it means no return value, RES is obtained ()
N1 + N2
}
 . 6) If no return value method explicitly declared ( statement Unit), then the method body even with the return keyword will not have a return value

 7) If no clear method returns a value or uncertain return type, the return value type can be omitted (or declared as Any)

 8) Any of a syntax structure can be nested syntax Scala other syntax structure (flexible), namely: the method may further declare / define methods, classes can be re-declared class, the method may then declare / definition method

{TestDef Object
DEF main (args: the Array [String]): Unit = {
// main function restatement / method defined in the sayHello
DEF the sayHello (name: String): String = {
DEF the sayHello (name: String): String = {
+ name "Hello"
}
the sayHello (name)
}
var = R & lt the sayHello ( "Terry")
the println ( "R & lt =" + R & lt) = R & lt Terry Hello //
}
}
 . 9) parameter Scala method, when the parameter declaration, directly assigned an initial value (default value), then the method is invoked, if the argument is not specified, then the default values. If the argument is specified, the default value of the real participants cover

{the Test Object
DEF main (args: the Array [String]): Unit = {
the println (SAYOK ())
the println (SAYOK ( "Tom")) // Default covered
}
DEF SAYOK (name: String = "Jack"): = {String
return name + "OK!"
}
}
10) If there are multiple methods parameters, each parameter value can be set, then this time, in the end is passed parameter to override the default value, is not assigned to the default value parameters not determined (default declaration order [left to right]). In this case, the name may be used with parameters

/ **
* @author huleikai
* @Create 2019-05-17 11:56
* /
Object TestDefArgs {
DEF main (args: the Array [String]): Unit = {
mysqlCon () // do not pass parameter default values are used
mysqlCon ( "127.0.0.1", 8080) // default parameters by an order corresponding cover
mysqlCon (pwd = "123456") // parameter name used with default values covering a
}

DEF mysqlCon (the Add: String = "localhost", Port: int = 3306,
User: String = "the root", pwd: String = "the root"): Unit = {
the println ( "the Add =" + the Add)
the println ( "Port =" + Port)
the println ( "User =" + User )
the println ( "pwd =" + pwd)
}
}
 . 11) formed Scala method default parameter val, and therefore can not be modified in the process

 Before 12) did not perform recursive method can not be inferred from the result type, must have a clear return type in use

 13) Scala method supports a variable parameter

SUM DEF (args: Int *): = Int {}
3.Scala Function
    Function and method substantially the same, but in the scala, the concept of functions is more important and widespread, and more flexible.

  ① the definition of a function

   A similar method to define rules:

def abs (x: Double) = if (x> 0) x else -x
  in a case where the function is not recursive function, scala return type can be inferred by an expression = back. However, once the function is recursive, then you need to display the specified return value type:

RES DEF (n-: Int): Int = IF (n-<0). 1 the else n-RES * (. 1-n-)
  ② anonymous function

   Scala anonymous functions defined syntax is very simple, the arrow on the left is the parameter list, the right is the body of the function. After using anonymous functions, our code more concise.

   The following expression to define the type of input that accepts a parameter of Int anonymous function:

val add = (x: Int, y: Int) => x + y
  anonymous function as defined above, in fact, such an approach is the following abbreviations:

The Function1 the Add new new = DEF [Int, Int] {
DEF Apply (X: Int): = X + Int. 1;
}
 the Add now available as a function, used as follows:

println (add (3, 4) )
 we may not be provided to the anonymous function parameters, as follows:

val emptyFunc = () => { println ( "Hello Scala!")}
 above we said, if you have a method when no parameter list, you can call the method name can be written directly, but no arguments anonymous function calls bring () parentheses

println (emptyFunc ())
interconversion The method and the use and functions
    as a function itself is actually Trait inherited object, it will function as a natural method for mass participation no problem parameters, corresponding to the custom method in java Student class objects as transmission parameters, the function may be passed as a parameter to the method, may be passed as a parameter of the function

  

   The process itself can not be directly used as parameters, but can be converted to a function of further mass participation, if the incoming parameter types meet the conditions of the method parameters in a method or function, then the compiler Scala default function to convert the transfer method enter

  

  Of course, the method may also be used the method name + _ + space conversion as a function of the method, as shown below:

  

Exception 5.Scala exception of
 ① Scala exception handling Examples

{the try
Val NUM = 10/0
} {the catch
Case EX: an ArithmeticException => the println ( "exception capture the arithmetic division by zero")
Case EX: Exception => the println ( "exception capture")
} the finally {
// final code to execute
the println ( "Scala the finally ...")
}
② custom exception class Scala

   In Scala, you can create your own exceptions. It is also known as custom exception. By extending the Exception class, and declare the custom exception class. Create your own custom exception message in class. Let's look at an example:
 

//声明一个异常类继承Exception
class InvalidAgeException(s: String) extends Exception(s) {}

class ExceptionExample {
@throws(classOf[InvalidAgeException])
def validate(age: Int) {
if (age < 18) {
throw new InvalidAgeException("Not eligible")
} else {
println("You are eligible")
}
}
}

object Demo {
def main(args: Array[String]) {
var e = new ExceptionExample()
try {
e.validate(5)
} catch {
case e: Exception => println("Exception Occured : " + e)
}
}
}
③ Scala异常处理总结

  1) Scala abnormal working mechanisms and Java, but Scala is not checked (compile) an exception, that is not unusual concept Scala compiler, exceptions are capturing process at runtime

  2) using the keyword throw, throw an exception object. All exceptions are subtypes of Throwable. throw expression is typed, it is Nothing, because Nothing is a subtype of all types, so throw expression can be used where needed type of

main DEF (args: the Array [String]): Unit = {
Val RES = Test ()
the println (res.toString)
}
DEF Test (): = {Nothing
the throw new new Exception ( "abnormal")
}
  3) in Scala , borrowing the idea to do pattern matching of abnormality match, thus, the catch block, a series of case clause is to match the corresponding exception. Similar java the switch case x: a code block

  4) abnormal capture mechanism with other languages ​​in the same, if an exception occurs, catch clauses are sequential capture. Therefore, in the catch clause, after the more specific exception Echizen rely on, the more popular the more by abnormal, if the former general exception write, write the specific exception in the post, also without error in scala , but this is a very bad programming style

  5) Scala provides the throws keyword to declare an exception. You can use methods defined unusual statement. It provides the function to the caller of this method may throw this exception information. It helps to call the function code is included in the processing and try-catch block in order to avoid abnormal program termination. In the scala, you can use annotations to declare throws an exception

def main(args: Array[String]): Unit = {
f11()
}
@throws(classOf[NumberFormatException]) //等同于NumberFormatException.class
def f11() = {"abc".toInt}
 
--------------------- 

Guess you like

Origin www.cnblogs.com/ly570/p/10947719.html