本文介绍了scala:在函数中定义默认参数(val)vs使用方法(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!

我试图用val实现,但是我得到一个语法错误,像这样:

(没有默认值,这个编译好了)

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

(但我无法得到这个编译...)

  scala> val function_with_default =(x:String =default)=> {x +!} 
< console>:1:error:')'expected'但是'='找到。
val function_with_default =(x:String =default)=> {x +!}
^

有什么想法?

解决方案

没有办法做到这一点。您可以得到的最好的对象是扩展了 Function1 Function0 的对象,其中 Function0 使用默认参数调用另一个apply方法。

  val functionWithDefault = new Function1 [String ,String]与Function0 [String] {
覆盖def apply = apply(default)
覆盖def apply(x:String)= x +!



$ b $ p
$ b

如果你更经常需要这样的函数,你可以将默认的apply方法到一个抽象类 DefaultFunction1 像这样:

  val functionWithDefault = new DefaultFunction1 [String,String](default){
覆盖def apply(x:String)= x +!


抽象类DefaultFunction1 [-A,+ B](默认:A)
使用Function0 [B]扩展Function1 [A,B] {
覆盖def apply = apply(default)
}


I have the following method:

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!

I'm trying to achieve the same with a val, but I get a syntax error, like this:

(with no default value, this one compiles ok)

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

(but I couldn't get this one to compile...)

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

any idea?

解决方案

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)
}

这篇关于scala:在函数中定义默认参数(val)vs使用方法(def)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:55