开发者

Why do people use _? as an identifier suffix?

开发者 https://www.devze.com 2023-01-28 16:59 出处:网络
I start reading Lift 开发者_开发技巧framework source code, I find that there\'re so many methods are defined using a name like methodName_? , is there a convention that _? has some special meaning?

I start reading Lift 开发者_开发技巧framework source code, I find that there're so many methods are defined using a name like methodName_? , is there a convention that _? has some special meaning?

def empty_? : Boolean = {}


You're unlikely to see the construct outside of the lift framework; I suspect that it's mostly Ruby-envy.

Almost any other Scala project will shy away from this syntax. Not because of the trailing question mark, but because it's yet another way to introduce underscores into your code - and the symbol is already far too heavily overloaded.

Based on an evaluation of multiple Scala projects, the notation can be reasonably described as non-idiomatic.

UPDATE

The reason that the underscore is required is to disambiguate from infix notation, in which:

x?y

would be read as

x.?(y)

with ? being a method name. Whereas:

x_?y

Clearly demarks x_? as being atomic.

The syntax is an example of what is formally known as a "mixed identifier", and is intended to allow definitions such as

def prop_=(v:String) = ... //setter
def unary_- = ... //prefix negation operator

It could (arguably) be considered a hack when similar construct is used simply to shove a question mark at the end of a method name.


The ? denotes that this is a predicate, a function returning Boolean. This convention goes back to Lisp, where ? (Scheme), p or -p (other Lisps, simulating the question mark with a "similar" letter) also denote predicates. Think of it as asking a question, "is the object empty?"

Scala will only allow mixed identifier names (containing alphanumerics and punctuation) if you separate them by _. E.g.,

scala> def iszero?(x : Int) = x == 0 
<console>:1: error: '=' expected but identifier found.
       def iszero?(x : Int) = x == 0
                 ^

doesn't work, but

scala> def iszero_?(x : Int) = x == 0          
iszero_$qmark: (x: Int)Boolean

does.

0

精彩评论

暂无评论...
验证码 换一张
取 消