What is trim() in Scala?

The trim() method is used to remove all the leading and trailing spaces that are present in the string. For example, if the string looks like, " Hello World " then there is a lot of empty space before the term “Hello” and after the term “World”.

The method trim() is used to remove these spaces.

Trim applied on some data

Title

Trim

" Hello World "

"Hello World"

" Lord of the rings "

"Lord of the rings"

" Fight club "

"Fight club"

Syntax

string.trim()

Using this method returns a string without any trailing of leading white spaces.

Code

Let’s understand it better with a coding example.

object Main extends App {
// apply trim on a string
val data = " Hello World ".trim()
// Display resultant data
println(data)
val data1 = "Lord of the rings ".trim()
// Display resultant data
println(data1)
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved