Scala basic learning 01

Posted by NottaGuru on Fri, 04 Mar 2022 20:20:13 +0100

The first Scala program

interactive programming

hadoop@master:~/desktop/ScalaLearn$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_162).
Type in expressions for evaluation. Or try :help.

scala> 1+1
res0: Int = 2

scala> println("Hello World!")
Hello World!

scala> 

Script form

gedit HelloWorld.scala
object HelloWorld {
	def main(args:Array[String]):Unit={
		println("Hello world!")
	}
}
scalac HelloWorld.scala  // Compile the source code into bytecode
scala HelloWorld  // Put the bytecode into the virtual machine to explain the operation
Hello world!

Define function identification number type

In China, mobile phone numbers are generally divided into three types: China Mobile, China Unicom and China Telecom. Write a function to identify the type of mobile phone number

data type

data typedescribe
Intinteger
FloatSingle-precision floating-point
DoubleDouble precision floating point number
StringCharacter sequence
Booleantrue or false
UnitIndicates no value, which is equivalent to void in Java. Unit has only one instance value, written as ()

Constant and Variable

There are two types of data in Scala, constant (also known as value) and variable. You can define constants through the val keyword and variables through var.
(1) Constant
Once a constant is defined, it cannot be changed, that is, it cannot be recalculated or re assigned.
Define the syntax format of a constant: val name:type=initialization
Because scala has the function of type inference, you can define constants without explicitly specifying their data types. Constant names are required to start with a letter or underscore followed by more letters, numbers, or underscores. Note that the dollar sign $, cannot be used in variable names.

Once val is initialized, it cannot be modified. If you forcibly modify the initial value of the variable, an error will be reported.

scala> val x=1+1
x: Int = 2

scala> val x:Int=1+1
x: Int = 2

scala> x=3
<console>:12: error: reassignment to val
       x=3
        ^

(2) Variable
A variable is an amount whose value may change during program operation. Variables can also be re assigned after they are defined. (you can only re assign values of the same type to variables, otherwise an error will be reported)

scala> var y=1
y: Int = 1

scala> var y:Int=1
y: Int = 1

scala> y=5
y: Int = 5

scala> y=1.5
<console>:12: error: type mismatch;
 found   : Double(1.5)
 required: Int
       y=1.5
         ^

array

scala declares an array as follows:

var z:Array[String]=new Array[String](num)or
var z=Array(Element 1,Element 2,...)
scala> var z:Array[String]=new Array[String](3)
z: Array[String] = Array(null, null, null)

scala> z(0)="baidu";z(1)="google";z(2)="biying"

scala> z
res1: Array[String] = Array(baidu, google, biying)

scala> var z:Array[String]=Array("baidu","google","biying")
z: Array[String] = Array(baidu, google, biying)
Basic operation (operation array arr)describe
arr.lengthReturns the length of the array
arr.headView the first element of the array
arr.tailView the elements in the array except the first element
arr.isEmptyDetermine whether the array is empty
arr.contains(x)Determine whether the array contains element x
scala> var z:Array[String]=Array("xing","wei","kun")
z: Array[String] = Array(xing, wei, kun)

scala> z.length
res3: Int = 3

scala> z.head
res4: String = xing

scala> z.tail
res5: Array[String] = Array(wei, kun)

scala> z.isEmpty
res6: Boolean = false

scala> z.contains("xing")
res7: Boolean = true

You can connect an array with the operator + +, or use the concat method. To use the concat method, you need to use import Array_ Import package.

scala> var arr1=Array(1,2,3)
arr1: Array[Int] = Array(1, 2, 3)

scala> var arr2=Array(4,5,6)
arr2: Array[Int] = Array(4, 5, 6)

scala> var arr3=arr1++arr2
arr3: Array[Int] = Array(1, 2, 3, 4, 5, 6)

scala> import Array._
import Array._

scala> var arr4=concat(arr1,arr2)
arr4: Array[Int] = Array(1, 2, 3, 4, 5, 6)

You can use the range method to create an interval array. You also need to import Array_
Generate an array with steps of 1 ~ 10 and 2

scala> import Array._
import Array._

scala> var arr=range(1,10,2)
arr: Array[Int] = Array(1, 3, 5, 7, 9)

function

In java, the function needs to use the return keyword to indicate the return value. scala functions can indicate the return value without the return keyword.

scala> def add(a:Int,b:Int):Int={a+b}
add: (a: Int, b: Int)Int

scala> def add(a:Int,b:Int):Int={
     | var sum=0;
     | sum=a+b;
     | return sum
     | }
add: (a: Int, b: Int)Int

scala> add(1,2)
res8: Int = 3
scala> :paste
// Entering paste mode (ctrl-D to finish)

object Test {
    def addInt(a:Int,b:Int):Int={
        var sum:Int=0
        sum=a+b
        return sum
    }
}

// Exiting paste mode, now interpreting.

defined object Test

scala> Test.addInt(2,3)
res9: Int = 5

Anonymous function

Anonymous function means that the function name is not given when defining the function. Anonymous functions = > are defined using the anonymous arrow

scala> (x:Int,y:Int)=>x+y
res10: (Int, Int) => Int = <function2>

scala> val addInt=(x:Int,y:Int)=>x+y
addInt: (Int, Int) => Int = <function2>

scala> addInt(1,3)
res11: Int = 4

Placeholders can be used if each parameter in a function appears at most once in the function_

scala> val addInt=(_:Int)+(_:Int)
addInt: (Int, Int) => Int = <function2>

scala> addInt(1,2)
res12: Int = 3

Higher order function - function as parameter

The function addInt, which defines the addition of integers, uses another function f with values a and b as parameters, and function f calls a and b as parameters.

scala> def addInt(f:(Int,Int)=>Int,a:Int,b:Int)=f(a,b)
addInt: (f: (Int, Int) => Int, a: Int, b: Int)Int

scala> addInt((a:Int,b:Int)=>a+b,1,2)
res13: Int = 3

Higher order function - function as return value

scala> def rectangle(length:Double)=(height:Double)=>(length+height)*2
rectangle: (length: Double)Double => Double

scala> val func=rectangle(4)
func: Double => Double = <function1>

scala> println(func(5))
18.0

Function coritization

scala> def addInt(a:Int,b:Int):Int=a+b
addInt: (a: Int, b: Int)Int

scala> addInt(1,2)
res16: Int = 3
scala> def addInt(a:Int)(b:Int):Int=a+b
addInt: (a: Int)(b: Int)Int

scala> addInt(1)(2)
res18: Int = 3

Task realization

(1) Use the array to store various types of mobile phone number segments respectively

scala> var yidong=Array(1340,1341,1342,1343,1344,1345,1346,1347,1348,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,178,147,1705)
yidong: Array[Int] = Array(1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 135, 136, 137, 138, 139, 150, 151, 152, 157, 158, 159, 182, 183, 184, 187, 188, 178, 147, 1705)

scala> val liantong=Array(130,131,132,155,156,185,186,176,145,1709)
liantong: Array[Int] = Array(130, 131, 132, 155, 156, 185, 186, 176, 145, 1709)

scala> val dianxin=Array(133,1349,153,180,181,189,1700,177)
dianxin: Array[Int] = Array(133, 1349, 153, 180, 181, 189, 1700, 177)

(2) Define the function to identify the mobile phone number segment

scala> def identify(x:Int)={
     | if(yidong.contains(x)){
     | println("This number belongs to China Mobile")
     | }else if(liantong.contains(x)){
     | println("This number belongs to China Unicom")
     | }else if(dianxin.contains(x)){
     | println("This number belongs to China Telecom")
     | }else{
     | println("This number does not belong to China")
     | }
     | }
identify: (x: Int)Unit

scala> identify(133)
This number belongs to China Telecom

Topics: Scala