Scala:从方法返回各种基础类的构造函数

Scala: Returning the constructor of various base classes from a method

在 Scala 中,我正在尝试 return 从方法中 类 构造多个基 类

Abstract class A
case class B(foo : Int, bar : Int) extends A
case class C(foo : Int) extends A

object D
{
    def foo(bar : Int) : _ => A = 
    {
        bar match
        {
            case 1 => B //return constructor of B
            case 2 => C //return constructor of C
        }
    }
}

我希望能够像这样使用它:

D.foo(1)(1,2) //用参数(1,2)构造B的实例

D.foo(2)(1) //用参数(1)构造C的实例

但是,这现在不起作用

我认为你真正想要的是一个工厂:

trait A {   def foo }

object D {

  private class B extends A {
    def foo(val a: Int, val b:Int): = { println("foo_ab") }
  }

  private class C extends A {
    def foo(cal a: Int): = { println("foo_a") }
  }

  // your 'factory' method
  def apply(bar: Int):A = {
    if (bar == 1) return new B
    else return new C
  }

}

从现在开始你可以使用它了:

val test = A(1) //Creates a B Object
val test2 = A(2) //creates a C Object

希望对您有所帮助

我正在扩展我的答案:

你也可以这样做:D.apply(1).foo(1,2) 假设 foo 是 class B

的一个方法

试试这个代码:

object D {
  def foo(bar: Int): Seq[Any] => A = {
    seq =>
      bar match {
        case 1 => B(seq(0).asInstanceOf[Int], seq(1).asInstanceOf[Int]) //return constructor of B
        case 2 => C(seq(0).asInstanceOf[Int]) //return constructor of C
      }
  }
}

D.foo return 函数从 seq 参数创建 A 实例。

此代码的柯里化版本:

object D {
  def foo(bar: Int)(seq: Seq[Any]): A =
    bar match {
      case 1 => B(seq(0).asInstanceOf[Int], seq(1).asInstanceOf[Int]) //return constructor of B
      case 2 => C(seq(0).asInstanceOf[Int]) //return constructor of C
    }
}

四处走动:

abstract class A
case class B(foo : Int, bar : Option[Int]) extends A
case class C(foo : Int, bar : Option[Int]) extends A

implicit def int2option(value : Int) : Option[Int] = Some[value]

object D
{
  def foo(bar : Int) : (Int, Option[Int]) => A =
  {
    bar match
    {
      case 1 => B.apply //return constructor of B
      case 2 => C.apply //return constructor of C
    }
  }
}

object HelloWorld {
  def main(args: Array[String]) {
    val b = D.foo(1)(1, 2)
    val c = D.foo(2)(1, None)

    println(b)
    println(c)
  }
}

试试这个: </p> <pre><code>trait A case class B(foo : Int, bar : Int) extends A case class C(foo : Int) extends A object D { def foo(bar : Int)(x : Int, y: => Int = 0) : A = { bar match { case 1 => B(x,y) case 2 => C(x) } } }

</p> <pre><code>scala> val b = D.foo(1)(2,3) b: A = B(2,3) scala> val c = D.foo(2)(3) c: A = C(3)