Configure and run Scala on IDEA

Here, java17 and Scala3.2.2 are used as demonstrations
scala version
. IDEA version is 2022.3.2.
IDEA version
First, you need to install the scala plug-in.
scala plugin
Of course, you can also install third one above to format you scala program!


example

I personally think that it is more convenient to choose Intellij for the Build system!
Then, just create project directly

Here is the Scala online programming website
with sample code:

/**
 * @author 一只小汪汪鸭
 * @description org.example
 * @data 10:12 17/02/2023
 * */
class  Person {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val c=matchAge(65)
    println(c)
  }
  def matchAge(age:Int)={
    
    
    var classify=if(age<12){
    
    
      "童年"
    }else if(age>=12 && age<30){
    
    
      "青年"
    }else if(age>=30 && age<50) {
    
    
      "中年"
    }else if(age>=30 && age<50){
    
    
      "壮年"
    }else{
    
    
      "老年"
    }
    classify
  }
}

It needs to be classchanged to object, as for why it should be changed, here is an explanation!

  • Scala class constructors include: primary constructor and auxiliary constructor
class  类名(形参列表) {
    
    	// 主构造器
	// 类 体
	def	this(形参列表) {
    
    	// 辅助构造器
	}
	
	def	this(形参列表) {
    
    	// 辅助构造器可以有多个...
	}
}
  • In Scala, classand objecthave different meanings and uses, respectively.

  • class is a keyword that defines a class and is used to define member variables and member methods of the class. In Scala, a class is just a template or blueprint for creating instances of objects. Therefore, if you only define a class without creating an instance, you cannot perform any operations.

  • object is a singleton object used to define static methods, variables and constants. In Scala, each object is a singleton, has only one instance, and can directly access the methods, variables and constants defined in it without creating an instance. Therefore, if you want to define some static variables, constants or methods in Scala, you should use object to define them.

  • When running a Scala program, there must be an entry point. When the program contains a single class, a static main method must be defined in the class as the program entry point. And when the program contains one or more objects, you can directly define the main method in the object as the program entry point without creating an instance.

  • Therefore, when you need to create an independent program in Scala, you should use object to define the entry point of the program, and define the main method in it.

Click this button:
click button

Guess you like

Origin blog.csdn.net/qq_54053990/article/details/129086860