ternary

Drupal 8 Twig ternary operator syntax

As a quick note, the Drupal 8 Twig template ternary operator syntax looks like this:

{{ foo ? 'FOO IS TRUE' : 'FOO NOT TRUE' }}

You can test it like this in a Drupal 8 Twig template theme file if you’d like:

{% set foo = true %}
{{ foo ? 'FOO IS TRUE' : 'FOO NOT TRUE' }}

That test will emit the string “FOO IS TRUE” to your web browser.

You can find more Twig information at this symfony.com page.

How to use a Scala if/then statement like a ternary operator

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.”

Problem

You’d like to use a Scala if expression like a ternary operator to solve a problem in a concise, expressive way.

Solution

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:

The Scala ternary operator syntax

Scala FAQ: What is the Scala ternary operator syntax?

In other programming languages there is a definite, unique ternary operator syntax, but in Scala, the ternary operator is just the normal Scala if/else syntax:

if (i == 1) x else y

The beauty of this is (a) it is just the normal if/else syntax, so you don't have to remember something else, and (b) it's easy to read.

The Ruby ternary operator syntax

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:

How to use the Perl ternary operator

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.

The Java ternary operator examples

Summary: This tutorial shares examples of the Java ternary operator syntax.

Interested in saying a lot while writing a little? In a single line of code, the Java ternary operator let's you assign a value to a variable based on a boolean expression (either a boolean field, or a statement that evaluates to a boolean result).

At its most basic, the ternary operator (also known as the conditional operator) can be used as an alternative to the Java if/then/else syntax, but it goes beyond that, and can even be used on the right hand side of Java statements.