[scala] omission of syntax

We till JAVA is verbose in terms of syntax, but JAVA is very readable.

The syntax in Scala is not as verbose as JAVA, but without losing readability, we record common syntax omissions here.

The first is that we can omit data types, because Scala has automatic type determination mechanisms.

Full writing var myVar : String = "Scala"; 

We can omit the type declaration and let it decide for itself var myVar = "Scala";

In fact, the method can also omit the return data type.

Complete writing def add(a: Int, b: Int): Int = { return a+b } //We define an add method, the parameters are two Int types, and the return value is Int type

We can also omit return, and the method returns the last calculation result as the return result.

 def add(a:Int,b:Int) :Int = { a+b }

We can omit the return type of the method and the equal sign here , and let the language decide for itself.

 def add(a:Int,b:Int)  { return a+b }

When the statement in our method block is only one line, we can omit the curly braces .

def add(a:Int,b:Int) :Int = a+b ;

But it's important to note that we either omit the return type and the equals sign, or we omit the curly braces. Both cannot be omitted at the same time.

def add(a: Int, b: Int) = a+b; // this is wrong!

Example

class Counter{

  private var value = 0;

  def add(): Unit = value+= 1//equivalent to def add() { value+=1 }

  def current() { value } //equivalent to def current(): Int = value;

}//Note that there is no i++ in scala, only i+=1.

When we call the parameterless method, we can also omit the parentheses after it.

var myCounter = new Counter; // parentheses omitted var myCounter = new Counter();

myCounter.add(); //Not omitted

println(myCounter.current); // omitted

Note that when the method has no parameters, it cannot be omitted when there are parameters.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324724740&siteId=291194637