scala: define default parameters in a function (val) vs using a method (def)

后端 未结 1 1451
夕颜
夕颜 2021-01-11 12:29

I have the following method:

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

scala         


        
相关标签:
1条回答
  • 2021-01-11 12:41

    There is no way to do this. The best you can get is an object that extends both Function1 and Function0 where the apply method of Function0 calls the other apply method with the default parameter.

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

    If you need such functions more often, you can factor out the default apply method into an abstract class DefaultFunction1 like this:

    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 讨论(0)
提交回复
热议问题