【问题标题】:Scala - How to create a combine ArrayList of functions with and without parametersScala - 如何创建带有和不带参数的函数的组合 ArrayList
【发布时间】:2021-04-09 08:30:25
【问题描述】:

假设我必须遵循:

def f1: Int ( or  def f1(): Int )
def f2 (x: Int): Int
def f3 (x: Int): Int
def f4: Int
...
...

注意:这里的'Int'只是一个例子

我想做......

class Container[T] {
  val values = mutable.ListBuffer.empty[T => Int]
  def addValue(value: T => Int) = values += v
  def doSome(t: T): Int = values.foldLeft[Int](0){ (complete, v) => complete + v(t) }
}

val ContainerWithParam = new Container[Int]
val ContainerWithoutParam = new Container[???]

ContainerWithParam.addValue(f2)
ContainerWithoutParam.addValue(f1)

val result = ContainerWithParam.doSome(1000) + ContainerWithoutParam.doSome(???)

一种解决方案是使用 Option[Nothing]

class Container[T] {
  val values = mutable.ListBuffer.empty[T => Int]
  def addValue(value: T => Int) = values += v
  def doSome(t: T): Int = values.foldLeft[Int](0){ (complete, v) => complete + v(t) }
}

def f1(nothing: Option[Nothing]): Int
val ContainerWithoutParam = new Container[Option[Nothing]]
ContainerWithoutParam.doSome(None)

但我认为这不是一个非常干净和漂亮的代码......

【问题讨论】:

    标签: scala types polymorphism


    【解决方案1】:

    如果def f1: Int = ??? 那么...

    val containerWithParam = new Container[Int]
    val containerWithoutParam = new Container[Unit]
    
    containerWithParam.addValue(f2)
    containerWithoutParam.addValue(_ => f1)
    
    val result = containerWithParam.doSome(1000) +
                 containerWithoutParam.doSome(())
    

    如果def f1(): Int = ??? 那么.addValue(_ => f1())

    【讨论】:

    • 您可以使用Function.const(f1()) 代替_ => f1()。这主要是口味问题,但我觉得它更干净一些。
    【解决方案2】:

    @jwvh 的答案是正确的,但作为替代方案,您可以为函数没有参数的情况创建一个单独的类。这可以重用原来的实现。

    class ContainerNoParam {
      private val container = new Container[Unit];
      def addValue(value: => Int): Unit = container.addValue(_ => value)
      def doSome(): Int = container.doSome(())
    }
    
    val ContainerWithParam = new Container[Int]
    val ContainerWithoutParam = new ContainerNoParam
    
    ContainerWithParam.addValue(f2)
    ContainerWithoutParam.addValue(f1)
    
    val result = ContainerWithParam.doSome(1000) + ContainerWithoutParam.doSome()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      相关资源
      最近更新 更多