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.

时间: 2024-08-06 12:27:15

Beginning Scala study note(2) Basics of Scala的相关文章

Beginning Scala study note(9) Scala and Java Interoperability

1. Translating Java Classes to Scala Classes Example 1: # a class declaration in Java public class Book{} # Scala equivalent of a class declaration class Book Example 2: # a Java class with a Construtor public class Book{ private final int isbn; priv

Beginning Scala study note(3) Object Orientation in Scala

1. The three principles of OOP are encapsulation(封装性), inheritance(继承性) and polymorphism(多态性). example: class Shape{ def area: Double = 0.0 } # supertype # subtypes class Rectangle(val width: Double, val height: Double) extends Shape{ override def ar

Beginning Scala study note(8) Scala Type System

1. Unified Type System Scala has a unified type system, enclosed by the type Any at the top of the hierarchy and the type Nothing at the bottom of the hierarchy. All Scala types inherit from Any. # Using Any, Book extends AnyRef, and x is an Int that

Beginning Scala study note(6) Scala Collections

Scala's object-oriented collections support mutable and immutable type hierarchies. Also support functional higher-order operations such as map, filter, and reduce that let you use expression-oriented programming in collections. Higher-order operatio

Beginning Scala study note(5) Pattern Matching

The basic functional cornerstones of Scala: immutable data types, passing of functions as parameters and pattern matching. 1. Basic Pattern Matching In Scala, your cases can include types, wildcards, sequences, regular expressions, and so forth. scal

Beginning Scala study note(7) Trait

A trait provides code reusability in Scala by encapsulating method and state and then offing possibility of mixing them into classes thus allowing code reuse. #define Trait Gliding scala> trait Gliding{ | def gliding(){ println("gliding")} |

Beginning Scala study note(4) Functional Programming in Scala

1. Functional programming treats computation as the evaluation of mathematical and avoids state and mutable data. Scala encourages an expression-oriented programming(EOP) 1) In expression-oriented programming every statement is an expression. A state

Programming In Scala Reading Note 3

Class and Object class TestClass { val some = 1 } 生成的class文件中会包含一个some()方法,并且这个方法是public的,也就是说类外可以通过类的对象来获取这个some的值 修改: class TestClass { private val some = 1 } 会生成一个private的some()方法,返回值也是some.但是现在类外是访问不到的 类的方法的参数默认是val类型的 副作用大部分用来修改一个属性的值或者开关一个I/O,只

Programming In Scala Reading Note 7

函数和闭包 1 成员方法 java中函数存在的方式,我们给一个类追加一个功能的途径就是给他追加一个方法. 2 本地方法 所谓的本地方法就是存在于一个方法内部的方法. 如果一个类中有一个方法是private的,且只有一个方法使用到他,那么这个方法完全可以被定义为一个本地方法 3 函数式一等公民 方法分为: 1 方法名称 def add 2 方法参数 (a:Int, b:Int) 3 赋值符号 = 4 方法体 a + b 其实,(a:Int, b:Int) => a + b,就构成了一个基本的函数了