14

我正在尝试为 scala 中的匿名函数设置默认值,因此无法找到任何解决方案。希望有人能帮助我。

我有以下结构,

case class A(id:Int = 0)

case class B(a:A)

object B {
     def func1(f:Int = 0)={
      ........
     }
 def func2(f:A => B = (how to give default value ?))={
        case Nothing => {
         //do something....
        }
        case _ => {
         //do some other thing......
        }
 }
} 

基本上,我想将参数作为可选传递。我怎样才能做到这一点?

4

3 回答 3

16

像任何其他默认参数一样:

scala> def test(f: Int => Int = _ + 1) = f
test: (f: Int => Int)Int => Int

scala> test()(1)
res3: Int = 2

或使用字符串:

scala> def test(f: String => String = identity) = f
test: (f: String => String)String => String

scala> test()
res1: String => String = <function1>

scala> test()("Hello")
res2: String = Hello

编辑:

如果要使用默认提供的函数,则必须()显式使用,否则 Scala 不会粘贴默认参数。

如果您不想使用默认功能并提供显式功能,只需自己提供:

scala> test(_.toUpperCase)("Hello")
res2: String = HELLO
于 2013-09-30T09:04:51.127 回答
1

使用隐式参数。在对象中放置参数的隐式值。除非您提供显式参数或您在调用范围内提供了另一个隐式值,否则将使用此方法。

case class A(id:Int = 0)

case class B(a:A)

object B {
  implicit val defFunc: A => B = {a: A =>  new B(a) }
  def func1(f:Int = 0)={
  }
  def func2(implicit func: A => B) = { ... }
} 

The differences between this method and Alexlv's method are

  1. This works with standalone functions as well as methods.
  2. The scope rules allow for providing appropriate overrides in appropriate scopes. Alex's method would require subclassing or eta-expansion (with partial application) to change the default.

I offer this solution since you are already using an object. Otherwise, Alexvlv's example is simpler.

于 2013-09-30T11:37:36.397 回答
0

The other answers show how to provide some existing default value, but if you want the default to do nothing (as suggested by case Nothing) then you can use Option/None.

 def func2(f:Option[A => B] = None)={
    case Some(f) =>
      //do something....
    case None =>
      //do some other thing......
 }


 func2()
 func2( Some(_ + 1) )
于 2019-09-12T06:32:04.413 回答