java - 有没有办法在 Scala 中的方法参数中声明一组指定的值?

标签 java scala methods

假设我有一种方法可以根据 status 获取 student_subject 表查询,并且此 status 可能是“失败” “已通过”“正在进行”

如何使用一种方法而不是 3 种不同的方法来完成此操作? 是否可以在方法参数中声明接受什么类型的String

最佳答案

只需使用特征和单例

sealed trait Status //sealed doesn't allow to extend this trait in another compilation unit
case object Failed extends Status
case object Passed extends Status
case object Ongoing extends Status

def getStidentSubject(status: Status) = status match {
   case Failed => ...
   case Passed => ...
   case Ongoing => ...
}

或者,您可以只匹配字符串,但它的类型安全性要差得多。

如果您需要 Scala 中更多类似枚举的功能(保留 ADT 的优势),我建议您使用 Enumeratum 库。

关于java - 有没有办法在 Scala 中的方法参数中声明一组指定的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43314026/

相关文章:

java - 如何获取 Java 8 流中所有元素的字符串表示形式

java - 使用缓冲阅读器在java中读取文本文件时获取空值

regex - Scala 正则表达式联合

ruby-on-rails - Rails 检查记录是否在第一位

c# - 数据库触发器还是代码中的常用方法?

java - 从类中引用 java.lang.annotation.Annotation?

java - 无法读取我发送到 Android 应用程序的 JSON 响应

scala - Spark : How do I pass a PartialFunction to a DStream?

scala - 将可变集合转换为不可变集合

C# 属性和方法