String.Empty Field


#1

Requesting built-in read only representation of the empty string similler to C# .NET has on MSDN
for example:

public class String /* some code */ {
    companion object {
        @JvmField
        public val Empty: String = ""
    }
}

Uses:

String.Empty

#2

I never understood the reason behind String.Empty and I’ve always refused to use it.
Some people tell me it’s more readable, which is something I completely disagree with. It’s like saying Math.plus(1, 3) is more readable than 1 + 3.


#3

Why do you need it? Just use "". It’s like asking for Integer.ZERO constant.


#4

0 is zero itself but “” are not empty string itself but opening and closing quotes. In my opinion just two quotes as, for example, a function argument look a bit ugly, and it’s a case when unnamed constant should be taken out as a property.
Of course, it’s a matter of taste, so why not to provide the choice to developers. Or at least to provide more usecases and explanations showing one variant is truly worse than another.


#5

The developers have the choice of declaring this constant in their own code if they find this more readable. No reason why this needs to be in the standard library.


#6

I think Microsoft did it for the same reasons we have an Integer cache in the Integer class and there is the static constant Boolean.TRUE, that is for performance. There can be many empty String instances in a program if you don’t have String.EMPTY.


#7

While it’s true that there can be many instances of empty string in a program, those empty strings that come from literal "" are usually interned by JVM. Therefore both String.EMPTY constant and any constant denoted by "" literal will be represented with the same empty string instance at run time.


#8

In C# (and .NET generally), string literals are always interned to avoid duplication and so there can never be more than one instance of “”. If you look at the code for String.Empty it actual refers to “” in the background so, like @ilogico, I could never understand the reason why some people insisted on using String.Empty instead.

Similarly, in Kotlin, I can’t really see why:

if (s.isEmpty()) ....

is often considered superior to the more direct:

if (s == "") ...


#9

(Side note: I was under the impression these were always interned. Maybe there’s an exception for strings of unusual size, though.)