In kotlin how to create a String say “hello” twice...
# getting-started
h
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
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
If you want to call the Java constructor you could write
Copy code
java.lang.String("hello") as String
But don’t 😄
🙈 1
j
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
Learning purpose I am noob would be better answer
👌 1