A fun thing about looking at different programming languages is that you get to see the unique features of each language. For instance, some people don’t like Lisp because of all of the parentheses, and then Haskell seems to counter that by saying, “Hey, here are a couple of ways to get rid of parentheses.”
Scala 2.13 introduced two new “chaining operations” named
tap. Here’s a quick look at how they work, plus a little extra fun at the end.
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.6, “How to use a Scala if/then statement like a ternary operator.”
You’d like to use a Scala if expression like a ternary operator to solve a problem in a concise, expressive way.
This is a bit of a trick problem, because unlike Java, in Scala there is no special ternary operator; just use an if/else expression:
Scala FAQ: Scala doesn't have the
-- operators; are the some similar operators or methods that I can use instead?
val fields are immutable, they can’t be incremented or decremented, but
var integer fields can be mutated with Scala’s
In Scala there are no
-- operators. You should instead use the
-= operators, as shown below. First the
scala> var i = 1 i: Int = 1 scala> i++ <console>:9: error: value ++ is not a member of Int i++ ^ scala> i += 1 scala> println(i) 2
PHP FAQ: Can you share an example of how to use the PHP modulus operator?
Sure, here are two examples of how to use the PHP modulus operator. In this first example, because the remainder (the modulus, or technically, the modulo) of 100 divided by 5 is zero, the string "a was 0" will be printed:
Here's a quick example of some Ruby source code, showing how I used Ruby's ternary operator in a method that prints a CSV record for a class I defined:
In most languages there is an operator named the "ternary" operator that lets you write concise if/then statements. This makes for less verbose, which is generally a good thing. Perl also has a ternary operator, and I'll demonstrate it here.
General syntax of the ternary operator
The general syntax for Perl's ternary operator looks like this:
test-expression ? if-true-expression : if-false-expression
Let's take a look at a brief example to demonstrate this.
Summary: This tutorial shows a collection of Perl if, else, and else if examples.
Here are some examples of the Perl if/else syntax, including the “else if” syntax, which is really elsif. (I wrote this because after working with many different languages I can never remember the “else if” syntax for most languages, and
elsif is pretty rare.)
The Perl if/else syntax
The Perl if/else syntax is standard, I don’t have any problems here: