簡體   English   中英

Java語法:將大小寫轉換為變量?

[英]Java syntax: switch case as variable?

在Java中,這種語法是可能的:

int a = 1;
int i = 0;
i = a == 1 ? 5 : 8;

因此在這種情況下,我將為5,因為a = 1。

開關盒是否有類似的語法 例如這樣:

int a = 1;
int i = 0;
i = switch (a) {
    case 1: 5; break;
    case 2: 8; break;
}

這樣我也將是5,因為a = 1?

沒有。

僅這是可能的:

switch (a) {
    case 1: i = 5; break;
    case 2: i = 8; break;
}

不,沒有這樣的語法,但是您可以將switch語句包裝在一個方法中並實現類似的行為:

public int switchMethod (int a)
{
     switch (a) {
        case 1: return 5;
        case 2: return 8;
        default : return 0;
    }
}

...
int i = switchMethod (1);

您也可以使用鏈式三元語句:

int i = (a == 1) ? 5
      : (a == 2) ? 8
      : 0;

遺憾的是,不支持此語法。 但是您可以使用Java 8模擬這種行為:

import java.util.Optional;
import java.util.function.Supplier;

public class Switch {

    @SafeVarargs
    public static <T, U> Optional<U> of(T value, Case<T, U>... cases) {
        for (Case<T, U> c : cases) {
            if (value.equals(c.getTestValue())) {
                return Optional.of(c.getSupplier().get());
            }
        }
        return Optional.empty();
    }

    public static <T, U> Case<T, U> when(T testValue, Supplier<U> supplier) {
        return new Case<T, U>() {
            public T getTestValue() {
                return testValue;
            }

            public Supplier<U> getSupplier() {
                return supplier;
            }
        };
    }

    public interface Case<T, U> {
        Supplier<U> getSupplier();

        T getTestValue();
    }
}

用法:

String s = Switch.of(1,
        when(0, () -> "zero"),
        when(1, () -> "one"),
        when(2, () -> "two"))
        .orElse("not found");
System.out.println(s);

當然,您可以調整代碼以適合您的需求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM