scala函数返回类型或者

时间:2016-02-28 01:54:17

标签: scala function return return-type

我在scala中有一个功能,根据条件返回 <{strong> nullList[Double]List[List[List[Double]]]。我使用了关键字Any来定义return type,它适用于我,但如果我尝试使用List的属性,例如&#39; length&#39;在返回的值上,它给我的错误为value length is not a member of Any。目前,我已将功能定义为:

def extract_val(tuple: Tuple3[String,List[Double],List[List[List[Double]]]]): (Any) ={
     /*
        do something here
     */
}

我试图找出一些方法,以便我可以在我的函数定义中定义或返回类型:

def extract_val(tuple: Tuple3[String,List[Double],List[List[List[Double]]]]): (either Type A or either Type B) ={
     /*
        if something :
          return null
        elif something:
          return Type A
        elif something 
          return Type B
     */
}

我使用OR operator作为(Type A || Type B),但我收到了一些错误not found type ||。任何帮助都非常有用。

1 个答案:

答案 0 :(得分:2)

如果你知道你的返回类型总是什么都不是(null)或A或B,那么使用Option[Either[A,B]]是最快的方法。

这个解决方案的主要限制是,为更多类型,C,D等扩展它将更难。

如果您需要可扩展性,则可以实现自己的OneOf类型。你可以在Scala中相对容易地做到这一点。

sealed trait OneOf[A,B,C]
case class First[A,B,C](a: A) extends OneOf[A,B,C]
case class Second[A,B,C](b: B) extends OneOf[A,B,C]
case class Third[A,B,C](c: C) extends OneOf[A,B,C]

这是一个简单的(玩具)用例:

def x(i: Int): OneOf[Int,Boolean,Double] =  i match {
   case 1 => First(10)
   case 2 => Second(true)
   case _ => Third(0.2)
}

scala> x(2)
res1: OneOf[Int,Boolean,Double] = Second(true)

scala> x(1)
res2: OneOf[Int,Boolean,Double] = First(10)

scala> x(2)
res3: OneOf[Int,Boolean,Double] = Second(true)

scala> x(3)
res4: OneOf[Int,Boolean,Double] = Third(0.2)

这是一个采用OneOf并以不同方式处理每个选项的方法。

def takeOneOf[A,B,C](x: OneOf[A,B,C]) = x match {
     case First(a) => println(s"A=$a")
     case Second(b) => println(s"B=$b")
     case Third(c) => println(s"C=$c")
}