2012-10-07 12 views
10

Mam następujący sposób:scala: zdefiniować parametry domyślne funkcji (val) vs użyciu metody (def)

scala> def method_with_default(x: String = "default") = {x + "!"} 
method_with_default: (x: String)java.lang.String 

scala> method_with_default() 
res5: java.lang.String = default! 

scala> method_with_default("value") 
res6: java.lang.String = value! 

staram się osiągnąć to samo z Val, ale dostaję błąd składni, tak:

(bez wartości domyślnej, ten kompiluje ok)

scala> val function_with_default = (x: String) => {x + "!"} 
function_with_default: String => java.lang.String = <function1> 

(ale nie mogłem dostać ten skompilować ...)

scala> val function_with_default = (x: String = "default") => {x + "!"} 
<console>:1: error: ')' expected but '=' found. 
     val function_with_default = (x: String = "default") => {x + "!"} 
              ^

jakiś pomysł?

Odpowiedz

5

Nie ma sposobu, aby to zrobić. Najlepsze, co można uzyskać, to obiekt rozszerzający zarówno Function1, jak i Function0, w którym metoda stosująca Function0 wywołuje inną metodę stosującą z parametrem domyślnym.

val functionWithDefault = new Function1[String,String] with Function0[String] { 
    override def apply = apply("default") 
    override def apply(x:String) = x + "!" 
} 

Jeśli częściej potrzebują takich funkcji, można czynnik poza domyślne zastosowanie metody do klasy abstrakcyjnej DefaultFunction1 tak:

val functionWithDefault = new DefaultFunction1[String,String]("default") { 
    override def apply(x:String) = x + "!" 
} 

abstract class DefaultFunction1[-A,+B](default:A) 
       extends Function1[A,B] with Function0[B] { 
    override def apply = apply(default) 
} 
+0

Function1 z Function0 jest dość sprytny, ale powiedziałbym, że jest to trochę śmierdzący. Tylko moja opinia tutaj. Żadna dyskusja nie jest przeznaczona. :) – pedrofurla

+1

BTW możesz użyć cukrów dla funkcji: 'new (String => String) z (() => String) {override def apply = apply (" default "); nadpisuj def zastosuj (x: String) = x + "!" } 'działa. – pedrofurla

+0

Zgadzam się, że to trochę śmierdzące, ale nie widzę rozwiązania, które nie jest. –