# User-defined literals in Java?

DevFeed: [User-defined literals in Java?](<https://devfeed.tech/articles/user-defined-literals-in-java-22008.md>)

Original publisher: [Read original article](<http://blog.joda.org/2019/03/user-defined-literals-in-java.html>)

Author: Stephen Colebourne (noreply@blogger.com)

Published: 2019-03-22T11:39:00Z

Content type: opinion

Language: en

Sources: [Stephen Colebourne](<https://devfeed.tech/sources/stephen-colebourne.md>)

Topics: [Java](<https://devfeed.tech/topics/java.md>)

Tags: [java](<https://devfeed.tech/tags/java.md>)

## AI overview

The article proposes adding user-defined literals to Java so classes could convert literal character sequences into instances such as Currency, LocalDate, Pattern, and URI. It discusses type inference, raw-string processing, and compile-time validation as required semantics.

## Source excerpt

Java has a number of literals for creating values, but wouldn't it be nice if we had more? Current literals These are some of the literals we can write in Java today: integer - 123, 12s, 1234L, 0xB8E817, 077, 0b1011_1010 floating point - 45.6f, 56.7d, 7.656e6 string - "Hello world" char - 'a' boolean - true, false null - null Project Amber is also considering adding multi-line and/or raw string literals. But there are many other data types that would benefit from literals, such as dates, regex and URIs. User-defined literals In my ideal future, I'd like to see Java extended to support some form of user-defined literals. This would allow the author of a class to provide a mechanism to convert a sequence of characters into an instance of that class. It may be clearer to see some examples using one possible syntax (using backticks): Currency currency = `GBP`; LocalDate date = `2019-03-29`; Pattern pattern = `strata\.\w+`; URI uri = `https://blog.joda.org/`; A number of semantic features would be required: Type inference Raw processing Validated at compile-time Type inference Type inference is of course a key aspect of literals. It would have to work in a similar way to the existing literals, but with a tweak to handle the new var keyword. ie. these two would be equivalent: LocalDate date = `2019-03-29`; var date = LocalDate`2019-03-29`; The type inference would also work with methods (compile error if ambiguous): boolean inferior = isShortMonth(`2019-04-12`); public boolean isShortMonth(LocalDate date) { return date.lengthOfMonth() < 31; } Raw processing Processing of the literal should not be limited by Java's escape mechanisms. User-defined literals need access to the raw string. Note that this is especially useful for regex, but would also be useful for files on Windows: // user-defined literals var pattern = Pattern`strata\.\w+`; // today var pattern = Pattern.compile("strata\\.\\w+"); Today, the `\` needs to be escaped, making the regex difficult to read. Clearly,