Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are Scala strings?

Sarvech Qadir

By definition, a string is a sequence of characters. Every string object in Scala is immutable/constant. Once created, the object cannot be changed.

This is how strings are saved
This is how strings are saved

Scala string methods

Like strings in other languages, Scala strings also support the use of string methods to manipulate the string. Notable methods include length(), concat(), substring(), trim().

  1. length(): Calculates length of a string.

  2. concat(): Joins two strings into one using the + operator.

  3. substring(): Extracts a portion of a string.

  4. trim(): Removes trailing spaces. For example, "hello ", will return “hello”, removing the extra spaces at the end.

Strings in Scala can be defined using two methods:

  1. var str = "String by method 1": In this method, the compiler encounters a string literal and creates a string object.
  2. var str: String = "String by method 2". In this method, the type is specified before the declaration of the string literal.


object Main extends App {
    var str1 = "Hello World"
    val str2: String = "Welcome to Educative"

    // Display both strings

    // display length
    println(str1 + ", Length: " + str1.length());
    println(str2 + ", Length: " + str2.length());

    // concat operation
    var new_str: String = str1.concat(str2)
    println("concatenated string: " + new_str)

    // substring take three character from index 0: start
    var subs: String = str1.substring(0,3)
    println("substring: " + subs)





Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring