Scala lets you specify method arguments using a named style. When you have methods or class constructors taking similar types of arguments, it becomes difficult to detect errors if you swap them by mistake. Let’s take the example of Person again. Instead of passing in an order of first name, last name, if we swap the order, Scala won’t complain:
Unfortunately, both parameters are of the same type, and the compiler can’t detect the mistake at compile time. But now, using named style arguments, you can avoid the problem:
The named arguments use the same syntax as a variable assignment, and when you use named arguments, the order doesn’t matter. You can mix the named arguments with positional arguments, but that’s usually a bad idea. When going for named arguments, always try to use a named style for all the arguments. The following example uses a named style for the first argument but not for the second. As mentioned earlier, it’s good practice to avoid this:
When using a named style, if the parameter name doesn’t match, the Scala compiler will complain about the value not being found. But when you override a method from a superclass, the parameters’ names don’t have to match the names in the superclass method. In this case, the static type of the method determines which names have to be used. Consider this example, where you have the Person trait and SalesPerson overriding the grade method and changing the parameter name in the process from years to yrs:
Here years won’t work because the type of the s instance is SalesPerson. If you force the type variable to Person, then you can use years as a named argument. I know this is a little tricky to remember, so watch out for errors like this:
The value of the named argument could be an expression like a method or block of code, and every time the method is called, the expression is evaluated:
The complementing feature to named arguments is default arguments. You’ve already seen one example of a default argument in the query example, where the last argument of the case class defaulted to NoOption:
- case class Query(q: DBObject, option: QueryOption = NoOption) {
- def sort(sorting: DBObject) = Query(q, Sort(sorting, option))
- def skip(skip: Int) = Query(q, Skip(skip, option))
- def limit(limit: Int) = Query(q, Limit(limit, option))
- }
- val skipOption = Skip (10, NoOption)
- val newQuery = Query(new BasicDBObject(), skipOption)
The copy method is using a named argument to specify the parameter that you’d like to change. The copy method generated by the Scala compiler for the Skip case class looks like the following:
- case class Skip(number: Int, anotherOption: QueryOption) extends QueryOption {
- def copy(number: Int = number, anotherOption: QueryOption = anotherOption) = {
- Skip(number, anotherOption)
- }
- }
In Scala, invoking the == method is the same as calling the equals method. The == method is defined in the scala.Any class, which is the parent class for all classes in Scala.
沒有留言:
張貼留言