简体   繁体   中英

scala: alias for a keyword?

is there a way to create an alias for a scala keyword? in particular i have some boilerplate syntax that involves "val" and in order to make it easier to read i'd like to be able to type something "@@" instead and have that translated to val.

Edit:

In some cases, it might be very convenient to be able to replace "lazy val", not just "val". The use case has to do with a function that acts as a python decorator. It looks like this:

lazy val function = Decorate(function_ _)
def function_(x: Int, ...) = { ... }

it would be a lot nicer if it looked like this:

@ function = Decorate(function_ _)
def function_(x: Int, ...) = { ... }

just so that there's not a val stacked on top of a def, where both names are extremely similar. (the function_ name is not meant to be called, so it's the cleanest to make the names similar.)

No, there isn't.

(filler so SO will let me post)

Ouch. This isn't particularly idiomatic Scala.

To start with, you're naming a method " function_ ", they're not the same thing, a method is simply a member of some class, a Function is an object in its own right (although a method can be "lifted" to a function by the compiler, in a similar fashion to the autoboxing of primitives).

Second, what is Decorate ? The initial uppercase letter suggests that it's a singleton, therefore an object and the only actual "Function" in that expression!

Could you post a bit more info as to what the method and decorator actually do, so that I can give you a better example as to how you might achieve the same in Scala?

I guess one could write a Scala Compiler Plugin to achieve this. At least the Eclipse Plugin actually uses the original Scala Compiler, so it might actually work nicely with the IDE.

Other then that: Daniel C. Sobral is correct: No, there isn't.

Still it sounds like a lot of trouble for a little gain.

If function_ is never meant to be called directly, why not write

lazy val function = Decorate { (x: Int, ...) => ... }

or even

/**
 * This version makes it more explicit that it's a function value.
 */
lazy val function: (Int, ...) => ReturnType =
   Decorate { (x, ...) => ... }

Some caution is advised: conciseness and terseness are two different things. Here, it looks like you're trying to buy a few keystrokes at a very high price in terms of readability.

Update:

If you really want to achieve a simpler syntax for this sort of thing, you will need a compiler plugin. If you're going to go that far, I'd suggest using an annotations-based syntax that's likely to be pretty intuitive for Java/Scala developers:

@decorate(Memoize)
def slowFn(i: Int) = { ... }

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