简体   繁体   中英

Why does Scala not allow a parameter name in a function type definition?

Scala does not allow one to say:

def m(f:(numer:Double,denom:Double)=>tan:Double) = {...}

Just like annotating variables with types means a variable at least has some documentation, so would allowing the variables in a function type definition provide some documentation. Since it would be optional, the programmer would decide when to do it. But the above is definitely more informative than:

def m(f:(Double,Double)=>Double) = {...}

Would this added flexibility break the language syntax?

The workaround could be found in using type aliases.

type Numer = Double
type Denom = Double
type Tan   = Double
def m(f:(Numer,Denom)=>Tan) = {...}

Having syntax in your way brings questions and ambiguity -- eg will compiler check that target function will have the very same variables names or not? (think about user who will stumble that feature you're proposing)

A middle-of-the road workaround, similar to om-nom-nom's, might be to have a Fraction class, which is composed of a numerator and denominator along with a more descriptive name for f. Something like:

case class Fraction(numerator: Double, denominator: Double) { ... }

...

def doSomething(getTangent: (Fraction) => Double) = { ... }

The weakness here is that there's nothing stopping someone from passing a function of type (Fraction) => Double which actually returns a sine, cosine, etc. So you may consider, instead of getTangent, using the name trigFunc or something like that.

As for your original suggestion, as has been mentioned already, I think you wouldn't want to enforce that the function implementation uses the same parameter names as in the type description, therefor parameter names in the type description are effectively just comments, not anything to be enforced by the compiler. So a scaladoc comment might serve the same purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM