Chota Bheem
Chota Bheem

Reputation: 1126

String values in Kotlin

In Java, if we do new String() we know it would create new string object and it would be different from the object created without 'new'(even if contents are same).

//Java    
System.out.println("First" == new String("First")); // false always

In Kotlin, if I try to create String even by creating StringBuilder, it would still be identical to that created without String(..).

//Kotlin
println("First" == String(StringBuilder("First"))) //true always

If the created String(StringBuilder(..)) is going to reuse same string value, why give constructor? Does it do any value add, looking for such use-case.

Thanks.

Upvotes: 3

Views: 2202

Answers (4)

Osusara Kammalawatta
Osusara Kammalawatta

Reputation: 133

In Java, == is referential equality, but in Kotlin == is structural equality. That means, in Kotlin == and string1.equals(string2) both do the same thing. And in Kotlin we use === for referential equality.

Upvotes: 1

Yohan Malshika
Yohan Malshika

Reputation: 743

To use referential equality you need to use === operator in kotlin. In java == operator use for referential equality. but in kotlin it is structural equality.

Upvotes: 1

earthw0rmjim
earthw0rmjim

Reputation: 19427

By using the == operator you're checking structural equality between the strings (whether they represent the same sequence of characters). The Java equivalent of your Kotlin comparison code above would be something like this:

Object.equals("First", new String(new StringBuilder("First"))); // true

To check reference equality in Kotlin, you need to use the === operator.

Check out the Kotlin reference on Equality.

Upvotes: 7

Ivan Samborskii
Ivan Samborskii

Reputation: 270

In Java when you use operator == you use referential equality. However, in Kotlin it is structural equality.

To use referential equality in Kotlin you need to use === operator.

You can check this doc page for more information: https://kotlinlang.org/docs/reference/equality.html

Upvotes: 5

Related Questions