I am trying to avoid constructs like this:
val result = this.getClass.getSimpleName
if (result.endsWith(\"$\")) result.init else result
Ok,
Rex Kerr’s answer expressed in basic Scala:
"Hi".getClass.getSimpleName match {
case x if x.endsWith("$") => x.init
case x => x
}
although I’m not sure what part of the if–else construct you want to optimise.
From Tony Morris' Lambda Blog:
I hear this question a lot. Yes it does. Instead of
c ? p : q
, it is writtenif(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 ;)
Since : by itself won't be a valid operator unless you are ok with always escaping it with back ticks :
, you could go with another character, e.g. "|" as in one of the answers above. But how about elvis with a goatee ?::
implicit class Question[T](predicate: => Boolean) {
def ?(left: => T) = predicate -> left
}
implicit class Colon[R](right: => R) {
def ::[L <% R](pair: (Boolean, L)): R = if (q._1) q._2 else right
}
val x = (5 % 2 == 0) ? 5 :: 4.5
Of course this again won't work if you values are lists, since they have :: operator themselves.
Since if-else constructions in Scala return a value, you can use this
val a = if (1 < 0) 1 else 2
More info: https://alvinalexander.com/scala/scala-if-then-ternary-operator-cookbook-examples
We can combine How to define a ternary operator in Scala which preserves leading tokens? with the answer to Is Option wrapping a value a good pattern? to get
scala> "Hi".getClass.getSimpleName |> {x => x.endsWith("$") ? x.init | x}
res0: String = String
scala> List.getClass.getSimpleName |> {x => x.endsWith("$") ? x.init | x}
res1: String = List
Is this adequate for your needs?