我在scala中有一个函数,它根据条件返回、、null或List[Double]或List[List[List[Double]]]。我使用关键字Any来定义return type,它适用于我,但是如果我试图在返回的值上使用List的属性,比如'length‘,就会给出错误的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 ||。任何帮助都是有用的。
发布于 2016-02-28 04:16:25
如果您知道返回类型总是为空(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")
}https://stackoverflow.com/questions/35677802
复制相似问题