ICU API proposal: use covariant return in clone() to avoid casts (ICU4J)

28 views
Skip to first unread message

Mihai Niță Ⓤ

unread,
Jul 2, 2025, 4:38:08 PMJul 2
to icu-design
Dear ICU team & users,

I would like to propose the following API for: ICU 78
Please provide feedback by: next Wednesday, 2025-07-09 (more if anything is controversial)
Designated API reviewer: Markus

Ticket: https://unicode-org.atlassian.net/jira/software/c/projects/ICU/issues/ICU-23140

Currently many of our classes implement a public Object clone() method.
This forces anyone using to cast:

BreakIterator b1 = BreakIterator.getWordInstance(locale);
BreakIterator b2 = (BreakIterator) b1.clone();

But starting with Java 5 one can use “covariant return types”.
Meaning that we can return the proper type from clone, eliminating the need for casting.

Old API example:
class Foo {
    @Override
    public Object clone() { ... }
}
// Using it requires cast
Foo foo = (Foo) oldFoo.clone();

Proposed API example:
class Foo implements Cloneable {
    @Override
    public Foo clone() { ... }
}
// Using it does not require cast anymore
Foo foo = oldFoo.clone();

I would like to propose the following changes for ICU 78:
  1. Identify ALL ICU4J classes that implement a clone() method returning an Object and change these methods to return the class type. (47 classes, see design doc)
  2. Mark all such classes as implementing Cloneable.
  3. Remove all existing casts related to clone() calls.
Design document:

Markus Scherer

unread,
Jul 2, 2025, 5:10:44 PMJul 2
to Mihai Niță Ⓤ, icu-design
sgtm thank you very much!
markus

Rich Gillam

unread,
Jul 2, 2025, 5:19:43 PMJul 2
to Markus Scherer, Mihai Niță Ⓤ, icu-design
Awesome!  I love it!

—Rich

On Jul 2, 2025, at 2:10 PM, Markus Scherer <marku...@gmail.com> wrote:

sgtm thank you very much!
markus

--
You received this message because you are subscribed to the Google Groups "icu-design" group.
To unsubscribe from this group and stop receiving emails from it, send an email to icu-design+...@unicode.org.
To view this discussion visit https://groups.google.com/a/unicode.org/d/msgid/icu-design/CAN49p6pqP7FdzAnc3keR01rusrFvYvpOFh%3DjBNqtFMYk-iox%2BA%40mail.gmail.com.
For more options, visit https://groups.google.com/a/unicode.org/d/optout.

Mark Davis Ⓤ

unread,
Jul 2, 2025, 6:05:39 PMJul 2
to Rich Gillam, Markus Scherer, Mihai Niță Ⓤ, icu-design

--
You received this message because you are subscribed to the Google Groups "ICU - Team" group.
To unsubscribe from this group and stop receiving emails from it, send an email to icu-team+u...@unicode.org.
To view this discussion visit https://groups.google.com/a/unicode.org/d/msgid/icu-team/ADFD0B3E-5F1E-4F97-9DBB-B2DB2E42FE6B%40apple.com.
Reply all
Reply to author
Forward
0 new messages