Scala variables and data types

Posted by nuttycoder on Sun, 02 Jan 2022 19:16:02 +0100

Variables and data types

notes

As like as two peas in Java, there is not much to say here.

// Single-Line Comments 

/*
  multiline comment 
*/

/*
 * Documentation Comments 
 */

variable and constant

Constant: a variable that will not be changed during program execution

// variable
// var variable name [: variable type] = initial value
var i:Int = 20
// constant
// val variable name [: variable type] = initial value
val j:Int = 10

No variables where constants can be used

Naming conventions for identifiers

The character sequence used by Scala when naming various variables, methods, functions, etc. is called an identifier. That is: any place where you can name yourself is called an identifier.

Naming rules

The identifier declaration in Scala is basically the same as that in Java, but the details will change. There are three rules:

  • Begin with a letter or underscore followed by letters, numbers, and underscores
  • Starts with an operator and contains only operators
  • Any string included in backquotes, even Scala keywords

String output

  • Connect via +
  • printf usage: string, passing value through%
  • String template (interpolation string): get variable value through $
object Test04_String {

  def main(args: Array[String]): Unit = {
    val name:String = "zihoo"
    val age:Int = 21

    // Connect via +
    println(age + "Year old" + name + "study scala")

    // *Used for string copying and splicing multiple times
    println(name * 3)

    // printf usage: string, passing value through%
    printf("%d Year old%s study scala\n", age, name)

    // String template (interpolation string): get variable value through $
    println(s"${age}Year old ${name}study scala")

    // Format template string
    val num:Double = 3.1415926
    println(f"The number is ${num}%1.2f")

    // Three quotation marks represent the string and keep the original format output of multi line string
    val sql =
      s"""
         |select *
         |from
         |  student
         |where
         |  name = ${name} and age = ${age}
         |""".stripMargin
    println(sql)
  }
}

keyboard entry

In programming, if you need to receive the data input by the user, you can use the keyboard to input statements to obtain it.

import scala.io.StdIn

object Test05_StdIn {

  def main(args: Array[String]): Unit = {
    // Input information
    print("Please enter your name:")
    val name:String = StdIn.readLine()

    print("Please enter your age:")
    val age:Int = StdIn.readInt()

    print(s"welcome ${age}Year old ${name}study scala")
  }

}

Read write file

There is no way to encapsulate writing files in scala. But we have learned before that Java methods can be written directly in Scala, so we can use Java methods to write files.

import java.io.{File, PrintWriter}
import scala.io.Source

object Test06_FileIO {
  def main(args: Array[String]): Unit = {
    // Read data from file
    Source.fromFile("src/main/resources/test.txt").foreach(print)

    // Write data to file
    val writer = new PrintWriter(new File("src/main/resources/output.txt"))
    writer.write("Hello Scala from Java")
    writer.close()
  }
}

data type

All data in Scala are objects and subclasses of Any

In Scala, data types are divided into two categories: value type and reference type. Both value type and reference type are objects

Scala data types still adhere to the principle of automatic conversion from low-precision value types to high-precision value types

StringOps in Scala is an enhancement to String in Java

Unit corresponds to void in Java. It is used for the position of the return value of the method, 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.

Null is a type, and only one object is null. It is a subclass of all reference types.

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

Integer type

Scala's integer type is used to store integer values, such as 12, 303456, and so on

data type length describe
Byte 1 8-bit signed complement integer. The range of values is - 128 - 127
Short 2 16 bit signed complement integer. The range of values is - 32768 - 32767
Int 4 32-bit signed complement integer. The range of values is - 2147483648 - 2147483647
Long 8 64 bit signed complement integer. The range of values is - 9223372036854775808 - 9223372036854775807

Character type

It can represent a single character, and the character type is char

Empty 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 determines that there is 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

Type conversion

Automatic type conversion

Automatic promotion 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

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

(byte, short) and char are not automatically converted to each other

Byte, short and char can be calculated. When calculating, they are first converted to int type

package chapter02

object Test08_DataTypeConversion {

  def main(args: Array[String]): Unit = {
    // Automatic promotion 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
    val a1: Byte = 10
    val b1: Long = 2200
    val result: Long = a1 + b1
    var resultInt: Int = (a1 + b1.toInt)

    // 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 a2: Byte = 10
    val b2: Int = a2
    var c2: Byte = b2.toByte

    // (byte, short) and char are not automatically converted to each other
    val a3: Byte = 10
    val b3: Char = 'b'
    // val c3: Byte = b3  // error

    // Byte, short and char can be calculated. When calculating, they are first converted to int type
    val a4: Byte = 10
    val b4: Short = 203
    val c4: Char = 'b'
    val result4: Int = a4 + b4

  }
}

In addition, Scala also provides a very powerful implicit conversion mechanism (implicit functions, implicit classes, etc.).

Cast type

The inverse process of automatic type conversion, which converts the numerical type with high precision to the numerical type with low precision. A forced conversion function should be added when using, but it may reduce the accuracy or overflow, so pay special attention.

object Test08_DataTypeConversion {

  def main(args: Array[String]): Unit = {
    // Cast type
    // Convert high precision to low precision
    val n1: Int = 2.5.toInt
    println(s"n1: ${n1}")
    val n2: Int = -2.7.toInt
    println(s"n2: ${n2}")

    // The strong conversion symbol is only valid for the nearest operator, and parentheses are often used to raise the priority
    val n3: Int = 2.3.toInt + 3.7.toInt
    val n4: Int = (2.3 + 3.7).toInt

    // Conversion of numeric type and String type
    // Value -- > string
    val number: Int = 27
    val str: String = number + ""
    println(str)

    // String --> number
    val number2: Int= "12".toInt
  }
}

Topics: Big Data