Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala Escape Characters

Scala Escape Characters

In Scala, escape characters are used to represent special characters that cannot be written directly in string literals.

An escape character begins with a backslash \ followed by a specific character, representing some special meaning or effect.

The following table lists common escape characters:

Escape character Description
\b Backspace
\t Tab
\n Line Feed
\f Form Feed
\r Carriage Return
\" Double quote
\' Single quote
\\ Backslash

In characters or strings, a Unicode character between 0 and 255 can be represented by an octal escape sequence, that is, a backslash \ followed by up to three octal digits.

If the sequence of characters after the backslash \ does not form a valid escape sequence, a compilation error will result.

The following example demonstrates the use of some escape characters:

Example

object

Test

{

   

def

main

(

args

:

Array

[

String

]

)

{

      println

(

"Hello\tWorld\n\n"

)

;

   

}

}

Run Example »

Running the above code produces the following output:



$ scalac Test.scala

$ scala Test

Hello    World

The following is a Scala program example showing the use of various escape characters:

Example

object

EscapeCharacterExamples

{

 

def

main

(

args

:

Array

[

String

]

)

:

Unit

=

{

   

val

backspace

=

"Hello\bWorld"

   

// "HelloWorld"

   

val

tab

=

"Hello\tWorld"

         

// "Hello    World"

   

val

newline

=

"Hello\nWorld"

     

// "Hello

                                       

// World"

   

val

formFeed

=

"Hello\fWorld"

     

// "Hello World"

   

val

carriageReturn

=

"Hello\rWorld"

// "World"

   

val

doubleQuote

=

"He said, "Hello, World!""

 

// "He said, "Hello, World!""

   

val

singleQuote

=

'"'

           

// '"'

   

val

backslash

=

"This is a backslash: \"

 

// "This is a backslash: "

   

// sample output

    println

(

s

"Backspace: $backspace"

)

    println

(

s

"Tab: $tab"

)

    println

(

s

"Newline: $newline"

)

    println

(

s

"FormFeed: $formFeed"

)

    println

(

s

"CarriageReturn: $carriageReturn"

)

    println

(

s

"DoubleQuote: $doubleQuote"

)

    println

(

s

"SingleQuote: $singleQuote"

)

    println

(

s

"Backslash: $backslash"

)

 

}

}

Running the above code produces the following output:

、

Backspace: HelloWorld

Tab: Hello    World

Newline: Hello

World

FormFeed: HelloWorld

CarriageReturn: World

DoubleQuote: He said, "Hello, World!"

SingleQuote: "

Backslash: This is a backslash: \

** Example Explanation:**