Scala:类似于Option(某些,无)的东西,但具有三种状态:某些,无,未知 [英] Scala: Something like Option (Some, None) but with three states: Some, None, Unknown

查看:81
本文介绍了Scala:类似于Option(某些,无)的东西,但具有三种状态:某些,无,未知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要返回值,当有人要求输入值时,请告诉他们以下三件事之一:

I need to return values, and when someone asks for a value, tell them one of three things:

  1. 这是价值
  2. 没有价值
  3. 我们没有有关此值的信息(未知)

情况2与情况3略有不同.示例:

case 2 is subtly different than case 3. Example:

val radio = car.radioType

  1. 我们知道值:返回无线电类型,说先锋"
  2. b.没有价值:返回无
  3. c.我们缺少有关这辆车的数据,我们不知道它是否有收音机

我想我可以扩展scala的None并创建一个Unknown,但这似乎是不可能的.

I thought I might extend scala's None and create an Unknown, but that doesn't seem possible.

建议?

谢谢!

更新:

理想情况下,我希望能够编写如下代码:

Ideally I'd like to be able to write code like this:

car.radioType match { 
   case Unknown => 
   case None => 
   case Some(radioType : RadioType) => 
}

推荐答案

这是准系统的实现.您可能想看一下Option类的源代码:

Here's a barebones implementation. You probably want to look at the source for the Option class for some of the bells and whistles:

package example

object App extends Application {
  val x: TriOption[String] = TriUnknown

  x match {
    case TriSome(s) => println("found: " + s)
    case TriNone => println("none")
    case TriUnknown => println("unknown")
  }
}

sealed abstract class TriOption[+A]
final case class TriSome[+A](x: A) extends TriOption[A]
final case object TriNone extends TriOption[Nothing]
final case object TriUnknown extends TriOption[Nothing]

这篇关于Scala:类似于Option(某些,无)的东西,但具有三种状态:某些,无,未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆