![](/img/trans.png)
[英]How to declare variable/method type referred from the return type of another method
[英]How to declare a method which may return 3 different kinds of type?
我想定義一個方法,但是它的返回類型有3種。
def findSelectedItem: ??? = { ... }
???
這里可能是Category
, Section
, Page
,但是我不確定如何找到合適的類型來表示它。
如果只有2,則可以使用Either[Type1, Type2]
,但現在為3。
我是否需要聲明類似Either
但具有3個類型變量的內容? 還是已經有我可以使用的東西了?
您可以嵌套Either
:
特定
case class Category(name: String)
case class Section(name: String)
case class Page(name: String)
和這樣的方法:
def f(name: String): Either[Category, Either[Section, Page]] = {
name match {
case "c" =>
Left(Category(name))
case "s" =>
Right(Left(Section(name)))
case "p" =>
Right(Right(Page(name)))
}
}
那么您可以對結果進行“模式匹配”:
Seq("c", "s", "p").map(f).foreach {
case Left(c) => println("C")
case Right(Left(s)) => println("S")
case Right(Right(p)) => println("p")
}
或者,創建自己的Either3
:
case class Either3[+A, +B, +C](left: Option[A], middle: Option[B],
right: Option[C])
object Left3 {
def apply[A, B, C](a: A): Either3[A, B, C] = {
Either3(Some(a), None, None)
}
def unapply[A, B, C](e: Either3[A, B, C]): Option[A] = {
e.left
}
}
object Middle3 {
def apply[A, B, C](b: B): Either3[A, B, C] = {
Either3(None, Some(b), None)
}
def unapply[A, B, C](e: Either3[A, B, C]): Option[B] = {
e.middle
}
}
object Right3 {
def apply[A, B, C](c: C): Either3[A, B, C] = {
Either3(None, None, Some(c))
}
def unapply[A, B, C](e: Either3[A, B, C]): Option[C] = {
e.right
}
}
接着
def f(name: String): Either3[Category, Section, Page] = {
name match {
case "c" =>
Left3(Category(name))
case "s" =>
Middle3(Section(name))
case "p" =>
Right3(Page(name))
}
}
和...一起
Seq("c", "s", "p").map(f).foreach {
case Left3(c) => println("C")
case Middle3(s) => println("S")
case Right3(p) => println("p")
}
您還可以使用抽象類:
abstract sealed class Item(val name:String)
case object Category extends Item("category")
case object Section extends Item("sections")
case object Page extends Item("page")
對象ItemFinder {
def apply(s: String):Item = s match{
case Category.name => Category
case Section.name => Section
case Page.name => Page
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.