Simple introduction to Scala

It should not be easy to master a language, but it should not be difficult to simply master some usage and use it. Scala and java have many commonalities. From the perspective of Java, it should be easy to enter Scala.

Configuring the Scala environment

Here I configure Scala version 2.11.8
1. First, configure the local environment variables

2. The plug-in of scala is installed in settings - > plugins

3. SDK is added to Libraries in Project Structure

Differences and commonalities between Scala and Java

Scala features

Scala extensible
Functional programming
JAVA compatible
Class library call
Concise grammar
Code line short
Type inference
Abstract control
Static typing (you can't change the type arbitrarily, var and val can only change the value)
Security reconfiguration
Support concurrency control
Strong computing power
Customize other control structures

Difference (difference of some concepts)

In Java

Scala is very compatible with Java. Here we simply define a Java class

public class Demo1Java {
    public void print(){
        System.out.println("Print java");

    public static void main(String[] args) {
        Demo1Java demo1Java = new Demo1Java();
        demo1Java.print();//This is the method called through the object of the class

        Demo1Java.main(args);//This is a method called through a class object

//        new Demo2Scala().print_scala();

        //Classes in Scala can be called directly in Java
        new Demo4ScalaStu().print();

Here we can see that in Java, if a method in a class is not added with static, it is just an ordinary member method, which must be called through the class object, that is, the following: (our print method is not decorated with static, but a simple method. When calling, we need to create a class object to call.)

Only static modified methods can be called directly through class objects (class names), which are as follows: (because the main method in Java is called by the virtual machine, that is, through the class object. The class object is an object loaded into memory by the. Class bytecode file generated by the compiled code. There is a static modifier in the main function. Removing the static will report an error, that is, the main function needs to be called through the class object.)

In Scala

The main method in Scala can only be run in object, that is, the class modified by object is equivalent to a static class, that is, the "class object" in which the code is loaded into the virtual machine. The methods and attributes in the class are equivalent to automatically adding static, which can be called directly through the "class object" (class name). It is a singleton mode

object Demo2Scala {
  val i = 10

    * Scala main method in
    * Methods in Scala cannot be decorated with static
    * def Define the keyword of a function
    * main Method name
    * args: Array[String] Parameter name: parameter type
    * Unit The return value type is equivalent to void in Java
    * {} Method body

  def print_scala(): Unit ={

  def print_s: String ={
    val s = "S"
    return s

  def main(args: Array[String]): Unit = {
    print("Hello World")



Java can directly call the classes in Scala and use the methods inside

Classes in Scala:

class Demo4ScalaStu {
  def print(): Unit ={
    println("Scala Stu")

Differences (some differences in use)

import{BufferedReader, FileReader}
import java.util

import{BufferedSource, Source}

object Demo5ScalaBase {
  //Basic syntax of scala
  def main(args: Array[String]): Unit = {
      * variable
      * You can use val and var to define variables. You don't need to specify the type, but you'd better specify the type
      * Variables modified with val cannot be modified. They are equivalent to constants
      * Variables modified with var can be modified
      * Use val if you can
    val i = 100
    var j = 200
    j = 300
    println(i+1)//This is not a modification of variables

    //Automatic inference type
    val k = 100
    //It is best to add the type manually
    val kk : Int = 200
    //If you don't know what type it is, use the object type
    val k1 :Object = "100"

    //Type conversion
    //Type conversion in Java
    val str1 = "123"
    //Type conversion in scala: as long as the data meets the requirements, you can directly type to +
    val i1 = str1.toInt

    //String type
    val str:String = "Hello,World"
    val strings = str.split(",")
    strings.foreach(println) //In this way, the traversal can be output directly
    println(strings{0}) //The output here needs {} parentheses

    val str2:String = "abc"+"def"
    val builder: StringBuilder = new StringBuilder()
    //You can use the $variable name to remove the value of the variable in the string. The bottom layer is StringBuilder
    val str3:String = "abc"
    val str4:String = "def"
    val str5:String = "hij"
    println(s"$str3,$str4,$str5")//Use s in front

    //File reading and writing
    //Java mode
    val br = new BufferedReader(new FileReader("data/students.txt"))
    var line:String = br.readLine()
    while (line!=null){
      line = br.readLine()
    println("*" * 50)

    //scala reads files
    val source: BufferedSource = Source.fromFile("data/students.txt")
    val iter: Iterator[String] = source.getLines() //Returns an iterator, but the iterator can only traverse once
    //foreach in scala
    for (elem <- iter) {
    println("*" * 50)

    //First simplification
    println("*" * 50)

    //The second simplification: chain call
    println("*" * 50)

scala object oriented programming

Construction method

class Student(id:String,name:String,age:Int){
  println("default constructor ")
  //Directly define the properties of the class
  val _id:String = id
  val _name:String = name
  val _age:Int = age


object Demo6ScalaClass {
  def main(args: Array[String]): Unit = {
    val stu: Student = new Student("001","Zhang San",21)

Overloading of construction methods

class Student(id:String,name:String,age:Int){
  println("default constructor ")
  //Directly define the properties of the class
  val _id:String = id
  val _name:String = name
  val _age:Int = age
  var _clazz:String = _

//  Overloading of the constructor requires re implementing the this method
//  The first line of code must call the default constructor
  def this(id:String,name:String,age:Int,clazz:String){
    //Call the default constructor
    _clazz = clazz


object Demo6ScalaClass {
  def main(args: Array[String]): Unit = {
    val stu: Student = new Student("001","Zhang San",21)

    val stu2:Student = new Student("002","Li Si",22,"Liberal arts class 1")


be careful:
//If the variable name starts with an underscore, it needs to be enclosed in curly braces
//If you want to call a method of a variable, you also need to enclose it in curly braces
//return you can omit the last line of code. The default value is the returned value


class A(id:String,name:String){
  println("A Construction method of")
  //Definition is assignment
  val _id:String = id
  val _name:String = name

  override def toString = s"A(${_id}, ${_name})"

  * Inherit or use the extends keyword
  * However, when inheriting, you need to call the constructor of the parent class
class B(id:String,name:String,age:Int) extends A(id,name){
  println("B Construction method in")
  val _age:Int = age

  override def toString = s"B(${_id}, ${_name},${_age})"

object Demo7ScalaExtend {
  def main(args: Array[String]): Unit = {
    val b: A = new B("001","Zhang San",21)


Sample class

object Demo8CaseClass {
  def main(args: Array[String]): Unit = {
    //When creating a sample class object, the new keyword can be omitted
    val stu: Stu = Stu("001","Zhang San",21,"male","Liberal arts class 1")

    //The parameters in the sample class are the properties of the class
    //The default value is assigned by val. if you want to modify it, you need to manually modify it to var
    stu.age = 22

  * Sample class: it will automatically add "get, set" methods to each attribute during compilation, and implement the serialization interface
case class Stu(id:String,name:String,var age:Int,gender:String,clazz:String)

Thank you for reading. I am shuaihe, a senior majoring in big data. I wish you happiness.

Tags: Java Scala

Posted on Thu, 04 Nov 2021 13:53:30 -0400 by dercof