简体   繁体   English

Scala函数返回类型为或

[英]scala function return type either or

I've a function in scala which returns either null or List[Double] or List[List[List[Double]]] as per condition. 我已经一个函数scala返回无论是 nullList[Double]List[List[List[Double]]]按条件。 I used the keyword Any to define the return type and it works for me but if i tried to use the properties of List like 'length' on the returned value it gives me error as value length is not a member of Any . 我使用了关键字Any来定义return type ,它对我有用,但是如果我尝试在返回值上使用List的属性,例如'length',则会出现错误,因为value length is not a member of Any Currently, i've defined function as : 目前,我已将功能定义为:

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

I'm trying to find out some way such that i can define either or return type in my function definition as : 我试图找出某种方式,以便我可以在函数定义中定义或返回类型为:

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

I used the OR operator as (Type A || Type B) but i got some error as not found type || 我将OR operator用作(Type A || Type B)但由于not found type ||而遇到了一些错误 . Any help would be really useful. 任何帮助将非常有用。

If you know that your return type is always going to be nothing (null) or A or B, then using Option[Either[A,B]] is the fastest way to do this. 如果您知道返回类型总是为空(空)或A或B,则使用Option[Either[A,B]]是最快的方法。

The main limitation of this solution is that it will be harder to expand it for more types, C, D, etc. 该解决方案的主要局限性在于,很难将其扩展为更多类型的C,D等。

If expandability is what you need, you can implement your own OneOf type. 如果您需要可扩展性,则可以实现自己的OneOf类型。 You can do this relatively easy in Scala. 您可以在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]

Here is a simple (toy) use case: 这是一个简单的(玩具)用例:

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)

Here is a method that takes a OneOf and handles each option differently. 这是一个采用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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM