Math escape in listings and surround white space

I want to use the double right arrow for some Scala code in listings. I thought I'd use the mathescape option and $\Rightarrow$. However, this "eats" whitespace around it, e.g. if I have

foo  $\Rightarrow$  bar


only one space character is used in front and after the arrow, as if it were

foo $\Rightarrow$ bar


How do I enforce the whitespace? Could I embed the unicode character \u21D2 for the arrow instead of using mathescape?

EDIT: So with the comments I managed to produce a math escaped command that has a width of exactly three space characters in the verbatim font:

\newcommand{\ScalaRA}{{}\hspace{-0.04ex}\Rightarrow\hspace{-0.08ex}{}}


However, the problem of eating the white space is still there:

\begin{lstlisting}
abc d     g     j
a   d  $\ScalaRA$g  $\ScalaRA$j
a   def$\ScalaRA$ghi$\ScalaRA$j
\end{lstlisting}


In the second line, after using $\ScalaRA$ for the first time, subsequent whitespace is contracted: After the g character there are two spaces but it is rendered only as one space:

So going in an out of the math mode leaves some "garbage" behind somehow. How to clean this up so that all three lines are perfectly aligned and the two space characters after g in the second line are respected?

• inserting "empty groups" around the symbol within the scope of math should insert the "usual" relation space: ${}\Rightarrow{}$ Nov 6, 2013 at 3:48
• Use \newcommand{\ScalaRA}{\ \ \Rightarrow\ \ } and then foo$\ScalaRA$bar. You could even use \quad instead of two manual spaces.
– Werner
Nov 6, 2013 at 7:49
• Thanks. The only problem with both of these ideas is that the extra spaces are measured in terms of the maths font and not the tt font. Ideally I would like to have the whole construction a multiple of the tt space width, so that vertical columns still align. Any ideas? Nov 6, 2013 at 8:55
• Please see my edit Nov 6, 2013 at 9:25

This is probably the most convenient way:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\lstset{
literate={⇒}{\ScalaRA}{1}
}
\newcommand{\ScalaRA}{\mbox{$\Rightarrow$}}
\begin{document}
\begin{lstlisting}
abc d     g     j
a   d   ⇒ g   ⇒ j
a   def ⇒ ghi ⇒ j
\end{lstlisting}
\end{document}


With the help of @barbara-beeton and @werner 's comments, I came up with this:

\newcommand{\ScalaRA}{{}\hspace{-0.04ex}\Rightarrow\hspace{-0.08ex}{}}


The exact hspacing will depend on the tt font size. The only caveat is that in each line after the first usage of the math escape, to get multiple spaces one has to put an empty escape $$ inbetween each two. Like so: \begin{lstlisting} abc d g j a d \ScalaRAg$$ $\ScalaRA$j
a   def$\ScalaRA$ghi$\ScalaRA$j
\end{lstlisting}