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

时间:2015-03-13 10:09:12

标签: function scala constructor

在Scala中,我试图从一个方法返回许多基类的构造函数,如下所示

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的实例

但是,现在这还不行

4 个答案:

答案 0 :(得分:3)

走来走去:

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

答案 1 :(得分:1)

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

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是B类的方法

答案 2 :(得分:0)

试试这段代码:

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返回从A参数创建seq实例的函数。

此代码的合理版本:

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

答案 3 :(得分:0)

试试这个:

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

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

scala> val b = D.foo(1)(2,3)
b: A = B(2,3)
scala> val c = D.foo(2)(3)
c: A = C(3)