The default parameters and parameter entry with the name of the function Scala

Scala default parameters 

In Scala when sometimes we call certain functions, we do not want to give specific values of the parameters, and want to use their own parameter default values, then you use the definition of default parameters when defining the function.

 

def sayHello(firstName: String, middleName: String = "William", lastName: String = "Croft") = firstName + " " + middleName + " " + lastName

 

 

If the parameter is not given, it will make the right turn from the application parameters

 

Scala and Java realize the difference between the default parameters  

Java

public void sayHello(String name, int age) {

  if(name == null) {

    name = "defaultName"

  }

  if(age == 0) {

    age = 18

  }

}

sayHello(null, 0)

 

Scala
def sayHello(name: String, age: Int = 20) {

  print("Hello, " + name + ", your age is " + age)

}

sayHello("leo")

 

With name parameter

When calling the function, or may not function in accordance with the order defined by the parameters to pass parameters to pass but with use of the parameter name.

sayHello(firstName = "Mick", lastName = "Nina", middleName = "Jack")

You may be mixed with an un-named parameter names and parameters, but not named parameter must be in the front row with parameter name .

sayHello("Mick", lastName = "Nina", middleName = "Jack")

 

Guess you like

Origin www.cnblogs.com/YuanWeiBlogger/p/11415513.html