scala:将方法添加到枚举中 [英] scala: add methods to an enum

查看:141
本文介绍了scala:将方法添加到枚举中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的枚举:

object ConditionOperator extends Enumeration {

  val Equal           = Value("equal")
  val NotEqual        = Value("notEqual")
  val GreaterOrEqual  = Value("greaterOrEqual")
  val Greater         = Value("greater")
  val LessOrEqual     = Value("lessOrEqual")
  val Less            = Value("less")

我想为每个枚举添加一个方法,以便我可以这样使用:

And I'd like to add a method to each enum so that I can use it like this:

def buildSqlCondition(field: String, operator: ConditionOperator.Value, value: String ) = {
  val sqlOperator = operator.toSql
  [...]

所以,ConditionOperator.Equal.toSql将返回=,而ConditionOperator.NotEqual.toSql将返回<>等...

So, ConditionOperator.Equal.toSql wuld return "=", and ConditionOperator.NotEqual.toSql would return "<>", etc...

但是我不知道如何定义一个toSql方法,以便每个枚举都可以看到它自己的值,并决定如何将它自己转换为一个sql操作符...

But I don't know how to define a toSql method, so that each enum can "see" it's own value and decide how to translate itself to a sql operator...

推荐答案

这是我从过去关于这个主题的各种搜索中发现的Scala 2.9.2的一个例子: p>

This is an example of what I have found for Scala 2.9.2 from various searches on the topic in the past:

object Progress extends Enumeration {
    type enum = Value

    val READY = new ProgressVal {
      val isActive = false
      def myMethod: Any = { .. }
    }

    val EXECUTE = new ProgressVal {
      val isActive = true
      def myMethod: Any = { .. }
    }

    val COMPLETE = new ProgressVal {
      val isActive = false
      def myMethod: Any = { .. }
    }

    protected abstract class ProgressVal extends Val() {
      val isActive: Boolean
      def myMethod: Any
    }
    implicit def valueToProgress(valu: Value) = valu.asInstanceOf[ProgressVal]
}
type Progress = Progress.enum




  • 隐含是使其可用的关键。

    • The implicit is key to making this usable.

      类型枚举类型进度有点多余我把这些概念作为我发现有用的东西来呈现这两个概念。

      The type enum and type Progress are somewhat redundant; I include them to present both concepts as something I've found helpful.

      为了给予信用,原来的想法来自于Sean Ross 在回答这一个是重复的问题

      To give credit where it's due, the original idea for this came from Sean Ross in a response to a question of which this one is a duplicate.

      这篇关于scala:将方法添加到枚举中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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