简体   繁体   English

Java相当于Ruby的`if condition`代码

[英]Java equivalent to Ruby's `code if condition`

This has probably been asked before but I can't seem to find anything useful in Google (probably I'm looking for it wrong) nor here. 可能以前有人问过这个问题,但是我似乎在Google找不到任何有用的东西(可能我找错了),也没有找到。

What is the equivalent (if there actually is one) of Ruby's code if condition in Java? code if condition Java中code if conditioncode if condition Ruby code if condition的等效代码(如果实际上只有一个)是什么?

Example in Ruby (taken from TutorialsPoint): Ruby中的示例(摘自TutorialsPoint):

$debug=1
print "debug\n" if $debug

In Java instead of doing 用Java代替

if (conditional) {
    doSomething();
}

I'd like to do something like 我想做类似的事情

doSomething() if (conditional);

If I do 如果我做

if (conditional) doSomething();

I get a warning with a suggestion to invert if. 我收到警告,建议将其反转。

You cannot do that in Java, it isn't legal syntax. 您无法在Java中执行此操作,这不是合法语法。

You can do, 你可以做,

if (conditional) doSomething();

or 要么

if (conditional) {
    doSomething();
}

or even change the signature of doSomething() to take a boolean and then 甚至将doSomething()的签名更改为boolean ,然后

doSomething(conditional);

but you cannot add your desired syntax to the language without writing a pre-compiler. 但是如果不编写预编译器,则无法在语言中添加所需的语法。

For more see JLS-14.9. 有关更多信息,请参见JLS-14.9。 The if Statement . if语句

There is no equivalent. 没有对等的东西。 Ruby's statement is more syntactic sugar than anything else, as you can write the if statement in the same manner as you would in Java. Ruby的语句比其他任何语句都更具语法糖,因为您可以以与Java相同的方式编写if语句。

For Java, you're stuck wrapping your expressions in if statements: 对于Java,您必须将表达式包装在if语句中:

if(conditional) {
    takeAction();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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