Variables and data types in Scala

Posted by alanlee79 on Sat, 15 Jan 2022 02:54:57 +0100

catalogue

1, Variables and constants

2, Identifier

Note: scala keyword

3, String

4, Keyboard input

5, Data type

 1. Integer type

2. Floating point type

3. Character type

4. Boolean type

5.Unit type, Null type and Nothing type

6, Type conversion

1. Automatic conversion of value type

2. Cast type

 3. Conversion between numeric type and String type

1, Variables and constants

var variable name [: variable type] = initial value example: var i:Int = 10

val constant name [: constant type] = initial value example: val j:Int = 20

matters needing attention:

(1) when declaring a variable, the type can be omitted and the compiler deduces automatically, that is, type derivation

(2) after the type is determined, it cannot be modified, indicating that Scala is a strong data type language.

(3) when declaring a variable, it must have an initial value

(4) when declaring / defining a variable, you can use var or val to modify it. The variable modified by var can be changed, and the variable modified by val cannot be changed.

(5) the object reference modified by var can be changed, while the object modified by val cannot be changed, but the state (value) of the object can be changed. (for example, custom objects, arrays, collections, etc.)

Code example:

object Hello {
  def main(args: Array[String]): Unit = {
    //When declaring a variable, the type can be omitted and the compiler deduces automatically, that is, type derivation
    var i1 = 10
    //Scala is a strong data type language. After the type is determined, it cannot be modified
    var i2: Int = 10
    i2 = "10" //report errors
    //Variable declaration must have an initial value
    var i3: Int//report errors
    //When declaring / defining a variable, you can use var or val to modify it. The variable modified by var can be changed, and the variable modified by val cannot be changed
    var i4: Int = 10
    val i5: Int = 20
    i4 = 30
    i5 = 40 //report errors
    //The object reference modified by var can be changed, while the object modified by val cannot be changed,
    // But the state (value) of the object can be changed. (for example, custom objects, arrays, collections, etc.)
    val stu01 = new stu()
    var stu02 = new stu()
    // var can modify the address value of the reference data type, but val can't
    stu01 = new stu() //report errors
    stu02 = new stu()
    // Whether the attribute value in the reference data type can change depends on whether the internal attribute is defined as var or val
    stu01.age = 26 //report errors
    stu01.name = "lss"
    //Defined in class as_ You can let the compiler automatically set the initial value
    println(stu02.i7)
    
  }
class stu {
      var name: String = "ls"
      val age: Int = 25
      var i7: Int = _
    }
}

2, Identifier

The character sequence used by Scala when naming various variables, methods, functions, etc. is called an identifier.

Naming rules: (1) begin with a letter underscore, followed by a numeric letter underscore. a1 a2_

(2) only + - * / #!

(3) the fields contained in backquotation marks can include 39 keywords

Note: scala keyword

  • package, import, class, object, trait, extends, with, type, for
  • private, protected, abstract, sealed, final, implicit, lazy, override
  • try, catch, finally, throw
  • if, else, match, case, do, while, for, return, yield
  • def, val, var
  • this, super
  • new
  • true, false, null
    var Int:String = "a" //In Scala, Int is a predefined character, not a keyword
    var _: String = "a" // A single underscore cannot be used as an identifier because_ It is considered a method
    println(_) // The IDEA does not report an error, but the operation reports an error

3, String

Basic usage of string

1. Splice through + sign

2. Repeated string splicing

3.printf: pass value through%

4. Get the variable value through $

5. Use three quotation marks and scala's stripMargin method. In Scala, stripMargin defaults to "|" as the connector

object test01 {
  def main(args: Array[String]): Unit = {
    //1. Splice through + sign
    println("hello"+"world")//helloworld
    //2. Repeated string splicing
    println("hello"*10)//hellohellohellohellohellohellohellohellohellohello
    //3.printf: pass value through%
    printf("hello %s world %d\n",1,2) //hello 1 world 2
    //4. Get the variable value through $
    var name = "ls"
    var age = 25
    val s1 = s"name:${name},age:${age}" //name:ls,age:25
    println(s1)
    //5. Long string
    println("1" +
      "2" +
      "3")//123
    //6. Apply three quotation marks and scala's stripMargin method. In Scala, stripMargin defaults to "|" as the connector
    println(
      """one
        |only
        |old
        |tiger
        |""".stripMargin) //one
                          //only
                          //old
                          //tiger
  }
}

4, Keyboard input

Input string: stdin readLine()

Input integer: stdin readInt()

Input float: stdin readDouble()

object test02 {
  def main(args: Array[String]): Unit = {
    print("Please enter your name")
    val name = StdIn.readLine()
    print("Please enter age")
    val age = StdIn.readInt()
    print(s"full name: ${name},Age: ${age}")
  }
}
//Please enter name ls
//Please enter age 25
//Name: ls, age: 25

5, Data type

1) all data in scala are objects and subclasses of Any.

2) data types in scala are divided into two categories: numeric type (AnyVa1) and reference type (AnyRef). Both value type and reference type are objects.

3)Scala data types still follow the automatic conversion from low-precision value types to high-precision values

4) StringOps in scala is an enhancement of String in Java

5)Unit: corresponds to void in Java. It is used for the position of the method return value, indicating that the method has no return value. Unit is a data type, and only one object is (). Void is not a data type, but a keyword.

6)Null is a type, and only one object is ru1l. It is a subclass of all reference types (AnyRef).

7) Nothing is a subclass of all data types. It is mainly used when a function has no explicit return value, because it can return the thrown return value to any variable or function.

 1. Integer type

data type

describe

Byte [1]

8-bit signed complement integer. The range of values is - 128 to 127

Short [2]

16 bit signed complement integer. The range of values is - 32768 to 32767

Int [4]

32-bit signed complement integer. The range of values is - 2147483648 to 2147483647

Long [8]

64 bit signed complement integer. The value range is - 9223372036854775808 to 9223372036854775807 = the (64-1) power of 2 - 1

object test03 {
  def main(args: Array[String]): Unit = {
    //Any code in scala will be executed as a code block, and finally the return value of the last line of code will be returned
    val i:Int = {
      5 + 4
      2
      6
    }
    //val unit:Unit= print(i)

    //val exception:Nothing = throw new RuntimeException()
    val i1 = 5
    //Scala integer types have a fixed representation range and field length, which are not affected by specific operations, so as to ensure the portability of scala programs
    //val i2:Byte = 128 / / error
    val i2:Byte = 126+1
    println(i2)
    var i3 = 1
    //var i1:Byte = 126 + i3 / / therefore, each line is a code block, which is edited line by line. At this time, the value of i3 is unknown and an error is reported
  }
}

2. Floating point type

data type

describe

Float [4]

32-bit, IEEE 754 standard single precision floating-point number

Double [8]

64 bit IEEE 754 standard double precision floating point number

object test04 {
  def main(args: Array[String]): Unit = {
    var i1:Float = 12.0f
    var i2:Double = 12.36
  }
}

3. Character type

(1) character constants are single characters enclosed in single quotation marks' '.

(2) \ t: a tab stop for alignment

(3) \ n: newline character

(4) \ \: indicates\

(5) \ ": indicates"

object test05 {
  def main(args: Array[String]): Unit = {
    //A character constant is a single character enclosed in single quotation marks' '
    val a1: Char = 'a' //a
    val a2: Char = 97  //a

    // \t: A tab stop to realize the function of alignment
    val a3: Char = '\t'
    println(a3)

    // \n: Newline character
    val a4: Char = '\n'
    println(a3 + 0) //9
    println(a4 + 0) //10

    // \: indicates\
    val a5: Char = '\\'
    println(a5 + 0) //92

    // \: indicates
    val a6: Char = '\"'
    println(a6 + 0) //34
  }
}

4. Boolean type

(1) Only true and false values are allowed for Booolean type data

(2) boolean type takes up 1 byte

val bo1: Boolean = true
val bo2: Boolean = false

5.Unit type, Null type and Nothing type

data type

describe

Unit

Indicates no value, which is equivalent to void in other languages. The result type used as a method that does not return any results. Unit has only one

Instance value, written as ().

Null

Null, null type has only one instance value null

Nothing

Nothing type is at the lowest level of Scala's class hierarchy; It is a subtype of any other type.

When a function is determined to have no normal return value, we can use Nothing to specify the return type. This has the advantage that we can assign the returned value (exception) to other functions or variables (compatibility)

Unit: unit has only one instance ()

def main(args: Array[String]): Unit = {
  val `unit`:Unit = {
    1+1
    println(1)
  }
  println(`unit`) //()
  //If the type of the marked object is unit, the returned value cannot be received
  val i:Unit = "hello"
  println(i) // Although Unit is a numeric type, it can receive reference data types, indicating that it does not receive return values
}

Null: a null class has only one instance object. Null is similar to a null reference in Java. Null can be assigned to any reference type (AnyRef), but cannot be assigned to a numeric type (AnyVal)

 var s:String = "hello"
    s = null
    println(s) //null
    
    var i2:Int = 5
    i2 = null //report errors

Nothing: can be used as the return type of a method without a normal return value, and the method will not return normally

 val value: Nothing = {
      println("hello")
      1 + 1
      throw new RuntimeException()
    }

6, Type conversion

1. Automatic conversion of value type

When Scala programs perform assignment or operation, types with low precision are automatically converted to numerical types with high precision. This is automatic type conversion (implicit conversion). The data types are sorted by precision (capacity):

(1) automatic lifting principle: when there are multiple types of data mixed operation, the system will first automatically convert all data into the data type with high precision, and then calculate.

(2) when assigning a value type with high precision to a value type with low precision, an error will be reported, otherwise, automatic type conversion will be carried out.

(3) (byte, short) and char are not automatically converted to each other because byte and short are signed values and char is unsigned

(4) byte, short and char can be calculated. When calculating, they are first converted to int type.

object test07 {
  def main(args: Array[String]): Unit = {
    //Automatic lifting principle
    val num:Double = 1 + 2.0f + 3.65
    //When assigning a value type with high precision to a value type with low precision, an error will be reported. Otherwise, automatic type conversion will be carried out
    val num1:Double = 2.0
    //num1 = 1 / / an error is reported
    //(byte, short) and char are not automatically converted to each other
    var c:Char = 'a'
    //byte, short and char can be calculated. When calculating, they are first converted to int type
    val a:Short = 20
    val b:Byte = 30
    println(a+b+c)
  }
}

2. Cast type

The inverse process of automatic type conversion, which converts the numerical type with high precision to the numerical type with low precision.

(1) To convert data from high precision to low precision, you need to use to force conversion

(2) The strong conversion symbol is only valid for the most recent operand, and parentheses are often used to raise the priority

val a1:Double = 2.3
    println(a1.toInt) //2
    println((a1+0.5).toInt) //rounding

 3. Conversion between numeric type and String type

(1) Basic type to String type (Syntax: just convert the value of basic type + "")

(2) String type to basic numeric type (Syntax: s1.toInt, s1.toFloat, s1.toDouble, s1.toByte, s1.toLong, s1.toShort)

     //Basic type to String type
    val s1:Int = 20
    println(s1+"")
    val s2: String = s1.toString
    //String type to basic type
    val str1 = "3.14"
    val double: Double = str1.toDouble

Topics: Scala Back-end