What is compareTo in Scala?

The compareTo function in Scala checks whether two strings are the same or not. It is applied on a string.

It takes in a single parameter: the string to compare with. It returns zero if both strings are the same, a negative number if the first string is less than the second, and a positive number if the first string is greater than the second.

The illustration below shows how compareTo works in Scala:

How compareTo works in Scala

Definition

The compareTo function is defined as follows:

int compareTo(String second)

Return value

The compareTo function returns zero if both strings are the same, a negative number if the first string is less than the second, and a positive number if the first string is greater than the second.

Negative and positive numbers are based on the difference in character values between the first and second strings.

Examples

The following example shows the compareTo function with the same strings:

Zero is returned.

object Compare extends App {
val string1 = "Apple"
val result = string1.compareTo("Apple")
println(result)
}

The following example shows the compareTo function with the first string less than the second:

A negative number is returned.

object Compare extends App {
val string1 = "Ant"
val result = string1.compareTo("Apple")
println(result)
}

The following example shows the compareTo function with the first string greater than the second:

A positive number is returned.

object Compare extends App {
val string1 = "Apple"
val result = string1.compareTo("Ant")
println(result)
}
Copyright ©2024 Educative, Inc. All rights reserved