Scala:DefaultParameterValues
lastmod 2020-09-11created 2020-09-112 edits
Scala offers the convenience of giving parameters default values so that callers can omit those parameters.
Example
In Java, it is not hard to find situations where numerous methods are overloaded just to provide default values for certain parameters of a large method. This is especially true of constructors.
public class HashMap<K,V> {
public HashMap(Map<? extends K,? extends V> m);
/** 기본 크기가 (16)이고 로드 팩터가 (0.75)인 새로운 HashMap의 생성 */
public HashMap();
/** 기본 로드 팩터가 (0.75)인 새로운 HashMap의 생성 */
public HashMap(int initialCapacity);
public HashMap(int initialCapacity, float loadFactor);
}
In reality there are only two constructors here: one that takes another map, and one that takes a capacity and a load factor. The third and fourth constructors let users of HashMap create an instance with the load factor and capacity set to default values that are probably useful in most cases.
A bigger problem is that the default values exist in both the Javadoc and the code. Keeping them up to date is easy to forget. To avoid this problem, a common approach is to add public constants whose values will be shown in the Javadoc.
public class HashMap<K,V> {
public static final int DEFAULT_CAPACITY = 16;
public static final float DEFAULT_LOAD_FACTOR = 0.75;
public HashMap(Map<? extends K,? extends V> m);
/** 기본 크기가 (16)이고 로드 팩터가 (0.75)인 HashMap을 생성 */
public HashMap();
/** 기본 로드 팩터가 (0.75)인 새로운 HashMap의 생성 */
public HashMap(int initialCapacity);
public HashMap(int initialCapacity, float loadFactor);
}
This reduces how much we keep repeating ourselves, but it makes the code even less expressive.
Scala adds direct support for this.
class HashMap[K,V](initialCapacity:Int = 16, loadFactor:Float = 0.75) {
// ...
}
// 기본 값을 사용
val m1 = new HashMap[String,Int]
// 초기 크기는 20, 로드 팩터는 기본 값
val m2= new HashMap[String,Int](20)
// 둘 모드를 오버라이드
val m3 = new HashMap[String,Int](20,0.8)
// 이름을 지정한 인수를 통해 로드 팩터만을 오버라이드
val m4 = new HashMap[String,Int](loadFactor = 0.8)
Remember that Named Arguments can be used with any default value.