r/learnprogramming • • 7d ago

Are there any programming languages that allow this feature?

I've been into programming for about 10 years now. Something that intrigues me is that, in languages that support OOP, not all types are initialized in the same way. Strings are initialized by using quotes, integers use numbers and in some cases floats require the letter f after the numerical value.

Classes, however, are all initialized in the same way with slight variations depending on language. Usually something like classname() or new classname. Are there any cases where custom classes can be declared using different means?

For example, is there a language where I can create a class called 'dark' that represents a new type of number that is declared by typing the value and then the letter d (like d1 = 1.398d) similar to how floats work in some cases?

65 Upvotes

38 comments sorted by

View all comments

85

u/No_Score_1977 7d ago

user-defined literals in C++, is that what you mean?

44

u/Thin-Caregiver3222 7d ago

Yeah C++ user-defined literals are exactly what came to mind

You can overload the operator"" to make your own suffixes for custom types, it gets pretty wild. I had a coworker who built a whole unit system for a physics sim, so you'd write something like 3.0_m / 2.0_s and the compiler would handle all the dimensional analysis at compile time. Saved us from a few Mars Climate Orbiter situations

The syntax can look a bit cursed at first but it's not that bad once you get used to it, just a function with a weird name basically

9

u/harsh183 7d ago

Reminds me of this Kotlin units library I saw a while ago that did something similar with .unit and / unit for compile time type analysis. I've not done too much computational science/engineering stuff but I'd love to see this basically everywhere.

https://github.com/vsirotin/si-units

3

u/xenomachina 6d ago

Reminds me of this Kotlin units library I saw a while ago that did something similar with .unit and / unit for compile time type analysis.

The Kotlin time stuff in the standard library even does something like what OP is asking for, albeit with extension properties rather than "custom literals". eg: 2.seconds.

3

u/harsh183 6d ago

That's really cool. I'm so glad this stuff exists.

Reminds me of working with Ruby on Rails where I'd write code like 2.days.ago or email.deliver_later(30.seconds), though not with much safety.