https://kotlinlang.org logo
#getting-started
Title
# getting-started
h

Hassaan

08/15/2022, 9:39 AM
In kotlin how to create a String say “hello” twice in heap memory? In java, we do this with the help of ‘new’ keyword : new String(“hello”)
j

Joffrey

08/15/2022, 9:42 AM
The Kotlin equivalent of
new String("hello")
would be
String("hello")
, but I think Kotlin prevented this by not providing this constructor. Why would you want to do that, though?
1
s

Sam

08/15/2022, 9:42 AM
If you want to call the Java constructor you could write
Copy code
java.lang.String("hello") as String
But don’t 😄
🙈 1
j

Joffrey

08/15/2022, 9:43 AM
You could also work around this by going through the byte array:
Copy code
String("hello".encodeToByteArray())
But don't 😄
👍 1
@Hassaan do you need this in real life, or were you just trying to construct an example to learn about reference equality vs value-based equality?
h

Hassaan

08/15/2022, 9:56 AM
Learning purpose I am noob would be better answer
👌 1
3 Views