首页 > 代码库 > Beginning Scala study note(2) Basics of Scala
Beginning Scala study note(2) Basics of Scala
1. Variables
(1) Three ways to define variables:
1) val refers to define an immutable variable;
scala> val x = 10 x: Int = 10 scala> x*x res4: Int = 100 scala> res4 + 1 # use result as a value res6: Int = 101 scala> res4 + res6 res7: Int = 201 scala> x = 202 # x is an ummutable variable <console>:8: error: reassignment to val x = 202 ^
2) var refers to define a mutable variable.
scala> var y = 10 y: Int = 10 scala> y = 11 y: Int = 11 scala> y = 10.5 # you can reassign a new value to y, but you cannot resassign the variable to a different type <console>:8: error: type mismatch; found : Double(10.5) required: Int y = 10.5 ^ scala> var z = 10.5 z: Double = 10.5 scala> z = 11 # Int numbers can be converted to Double numbers z: Double = 11.0
3) lazy val variables are calculated once, the first time the variable is accessed. Only vals can be lazy variables. You would use a lazy val if the variable may not be used and the cost of calculating it is very long.
2. Scala Type Hierarchy
(1) Any, AnyVal and AnyRef
Class Any is the root of the Scala class hierarchy and is an abstract class. AnyVal and AnyRef extend Any. All other types descend from AnyVal and AnyRef.
(2) Numeric Types
1) Basic type
Scala supports the ability to automatically convert numbers from one type to another in the order:
Byte->Short->Int->Long->Float->Double
scala> val x: Byte = 30 x: Byte = 30 scala> val y: Short = x y: Short = 30 scala> val z: Double = x z: Double = 30.0
Scala does not allow automatic conversion in the order reverse from mentioned earlier.
scala> val x: Long = 40 x: Long = 40 scala> val y: Int = x <console>:8: error: type mismatch; found : Long required: Int val y: Int = x ^
(3) Boolean Type: limited to true or false.
scala> val x = !false x: Boolean = true
(4) Char Type
scala> val x = ‘X‘ x: Char = X
(5) Unit Type: to define a function that doesn‘t return data.
scala> val empty = ()
empty: Unit = ()
(6) Nothing and Null Types
Keyword null is a subtype of all reference types(AllRef引用类型), not a subtype of value type(值类型).
Nothing is a subtype of every other type. Nothing can signals abnormal termination. It‘s a trait that is guaranteed to have zero instances.
(7) String
String interpolation(插补) in scala is to combine your values inside a string variables. The notation is an s prefix added before the first double quote of the string. Then $ can be used to reference the variable.
scala> val bookTitle = "Begging Scala" //create a String bookTitle: String = Begging Scala scala> s"Book title is ${bookTitle}" // String interpolation res0: String = Book title is Begging Scala
(8) functions
A scala method is a part of a class that has a name and a signature, whereas a function in scala is a complete object that can be assigned to a variable.
1) Function without Parameter
scala> def hello() = {"Hello World!"} // "=" is used as a separator between the method name an the method body hello: ()String scala> hello // invoke this function with hello() or hello res1: String = Hello World! scala> hello() res3: String = Hello World! scala> def hello() = "Hello World!" // remove the parentheses hello: ()String
2) Function with Parameters
scala> def square(i: Int) = {i*i} // the body are expressions, where the final line becomes the return value of the function square: (i: Int)Int scala> square(2) res5: Int = 4 scala> def add(x: Int, y: Int) = {x+y} add: (x: Int, y: Int)Int scala> add(3,6) res6: Int = 9
(9) Arrays, Lists, Ranges and Tuples
1) Arrays
scala> var books: Array[String] = new Array[String](3) // one way to define books: Array[String] = Array(null, null, null) scala> var books = new Array[String](3) // Simplifying Array Declarations books: Array[String] = Array(null, null, null) scala> var books = Array("Beginning Scala","Beginning Java","Beginning Groovy") // another way to define books: Array[String] = Array(Beginning Scala, Beginning Java, Beginning Groovy) scala> books(0)="Beginning Scala" // Assigning values or accessing indivaldual elements scala> books(1)="Beginning Java" // The index of the firt element of an array is 0 scala> books(2)="Beginning Groovy" scala> println(books(0)) Beginning Scala
2) Lists
All elements have the same type like arrays, the difference is elements of a list cannot be changed by assignment. There are two ways to create a list: just like you create arrays or use :: cons operator.
val empty= List() // Note the type of the list is Nothing empty: List[Nothing] = List() scala> val books:List[String] = List("Beginning Scala","Beginning Java","Beginning Groovy") books: List[String] = List(Beginning Scala, Beginning Java, Beginning Groovy) scala> print(books(0)) Beginning Scala scala> val empty = Nil // Nil also represents the empty list. empty: scala.collection.immutable.Nil.type = List() scala> val books = "Beginning Scala" :: ("Beginning Groovy" :: ("Beginning Java" :: Nil)) // list can be defined using a tail Nil and :: books: List[String] = List(Beginning Scala, Beginning Groovy, Beginning Java) scala> val books = "Beginning Scala" :: "Beginning Java" :: "Beginning Groovy" :: Nil books: List[String] = List(Beginning Scala, Beginning Java, Beginning Groovy) scala> books.head // return the fisrst element of a list res6: String = Beginning Scala scala> books.tail // return a list consisting of all elements exception the first element res7: List[String] = List(Beginning Java, Beginning Groovy)
3) Ranges
Ranges can be defined by their start, their end, and the stepping value.
scala> 1 to 5 // Creating Range Using the Method "to" res12: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5) scala> 1 until 5 // Creating a Range using the "Util" Method res13: scala.collection.immutable.Range = Range(1, 2, 3, 4) scala> 1 to 20 by 4 // Creating a Range using the method "by" res14: scala.collection.immutable.Range = Range(1, 5, 9, 13, 17)
4) Tuples
A tuple is an ordered container of two or more values of same or different types. There is no way to iterate through elements in a tuple. It‘s only a container for more than one value.
Two ways to create a tuple:
① By writing your values separated by a comma and surrounded by a pair of parentheses
② By using a relation operator(->)
scala> val tuple = (1,false,"Scala") tuple: (Int, Boolean, String) = (1,false,Scala) scala> val tuple2= "title" -> "Beginning Scala" tuple: (String, String) = (title,Beginning Scala) scala> tuple._3 // Accessing an Element of the Tuple Using Index res0: String = Scala
2. Built-in Control Structures
(1) If
The result of if expressions is always Unit. The result of if/else is based on the type of each part of the expression.
scala> if(exp) {println("Line one"); println("Line two")} scala> val i : Int = if(exp) 1 else 3 scala> val i: Int = if(false) 1 else {val j = System.currentTimeMillis; (j%100L).toInt} i: Int = 57
(2) While Loops
While and do...while are called loops, not expressions. The type of the result is Unit.
while(exp) println("Working...") while(exp){ println("Working...") }
(3) For Comprehension
1) The left-arrow operator is called a generator because it generates corresponding values from a collection to be used in an expression.
scala> val books = List("Beginning Scala","Beginning Groovy","Beginning Java","Scala in easy steps","Scala in 24 hours") books: List[String] = List(Beginning Scala, Beginning Groovy, Beginning Java, Scala in easy steps, Scala in 24 hours) scala> for(i<-books) println(i) Beginning Scala Beginning Groovy Beginning Java Scala in easy steps Scala in 24 hours
2) Filters
A filter is used to filter the collection when you do not want to iterate through the entire collection.
scala> for(book<-books | if(book.contains("Scala"))) println(book) Beginning Scala Scala in easy steps Scala in 24 hours
3) Variable Binding
You can define variables inside for expressions. Even reuse these variables within the body of your for expression.
scala> for{ book <- books ; bookVal = book.toUpperCase()}println(bookVal) BEGINNING SCALA BEGINNING GROOVY BEGINNING JAVA SCALA IN EASY STEPS SCALA IN 24 HOURS
Note bookVal is not declared as a val, but you can still reuse it. This proves to be very useful in situations where you want to transform the elements in your collection while looping through them.
4) Yielding
In for expression, you can use the yield keyword to generate new collections. The type of the collection generated from the for expressions is inferred from the type of the collection being iterated over.
scala> var scalabooks = for{ | book <- books | if book.contains("Scala") | } yield book scalabooks: List[String] = List(Beginning Scala, Scala in easy steps, Scala in 24 hours)
The filtered result is yielded as a value named book. The result is accumulated with every run inside the for loop, and thus accumulated collection is assigned to the value scalabooks
(4) Try expressions
All exceptions in Scala are unchecked, there is no concept of checked exception.
1) throw new Exception("some exception...")
2) try{ throw new Exception("some exception...")}finally{println("This will always be printed")}
The try/catch construct in Scala is an expression that results in a value and that the exception in Scala can be pattern matched in the catch block instead of providing a separate catch clause for each different exception. It is possible to wrap a call in a try/catch and assign a default value if the call fails.
scala> try{Integer.parseInt("dog")}catch{case _: Throwable => 0} res10: Int = 0 scala> try{Integer.parseInt("44")}catch{case _: Throwable => 0} res11: Int = 44
Calling Integer.parseInt and defaulting to 0 if an exception is thrown.
Beginning Scala study note(2) Basics of Scala