Ternary Operator Similar To ?:

前端 未结 5 1204
小蘑菇
小蘑菇 2020-12-07 18:11

I am trying to avoid constructs like this:

val result = this.getClass.getSimpleName
if (result.endsWith(\"$\")) result.init else result

Ok,

5条回答
  •  春和景丽
    2020-12-07 18:49

    From Tony Morris' Lambda Blog:

    I hear this question a lot. Yes it does. Instead of c ? p : q, it is written if(c) p else q.

    This may not be preferable. Perhaps you’d like to write it using the same syntax as Java. Sadly, you can’t. This is because : is not a valid identifier. Fear not, | is! Would you settle for this?

    c ? p | q
    

    Then you’ll need the following code. Notice the call-by-name (=>) annotations on the arguments. This evaluation strategy is required to correctly rewrite Java’s ternary operator. This cannot be done in Java itself.

    case class Bool(b: Boolean) {   
      def ?[X](t: => X) = new {
        def |(f: => X) = if(b) t else f   
      } 
    }
    
    object Bool {   
      implicit def BooleanBool(b: Boolean) = Bool(b) 
    }
    

    Here is an example using the new operator that we just defined:

    object T {   val condition = true
    
      import Bool._
    
      // yay!   
      val x = condition ? "yes" | "no"
    }
    

    Have fun ;)

提交回复
热议问题