0

Motivation

Consider the following snippet of code:

def paint(numCoats, height):
    ...

numCoats = 2
height = 3

paint(numCoats, height)

Even though numCoats and height are both stored as integers, under very few circumstances should they be confused. Writing paint(height, numCoats) should produce an error, no less (preferably compile-time).

Unsatisfactory solutions

  1. Creating a wrapper class every single time. Writing a long clunky class definition for every single parameter + having to import that class in all calling code is unacceptable.

  2. Hungarian notation (in either the parameter name, variables, or both). While there are legitimate (and illegitimate) applications of Hungarian notation, in this case it would be (a) clunky and (b) not prevent mistakes.

  3. Keyword arguments. While keyword arguments would solve the above issues, it might not solve other similar issues.

Summary of requirements

  • A minimalist way of just declaring literals or objects to belong to a certain type, and enforcing such type restrictions in scenarios like passing parameters to functions.

I’m not confident I’ve articulated this question well; please comment if I can clarify anything!

1

In Scala, you can use traits to achieve more or less what you want (I have not tried this example but something similar should work):

train NumCode {}
trait Height {}

def paint(numCode: Int with NumCode, height: Int with Height) { ... }

def main() {
  val numCode : Int with NumCode = 2
  val height : Int with Height = 3
  paint(numCode, height)
}

You still need to declare the marker traits, but I don't see how a language would get rid of that, but still allowing you to pass parameters that are not called exactly like the arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.