当前位置: 首页>>代码示例>>Java>>正文


Java Option类代码示例

本文整理汇总了Java中com.googlecode.totallylazy.Option的典型用法代码示例。如果您正苦于以下问题:Java Option类的具体用法?Java Option怎么用?Java Option使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Option类属于com.googlecode.totallylazy包,在下文中一共展示了Option类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: convert

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
/**
 * Converts a Money value to the specified currency.
 *
 * The conversion first attempts to use an existing exchange rate for the two currencies in question.
 * If no direct exchange works, a cross rate (limited to 1 hop) will be calculated and used.
 * If no cross rate can be calculated a NoSuchElementException is thrown
 *
 * @param money  Money to be converted
 * @param currency Currency to be converted to
 * @return
 * @throws NoSuchExchangeRateException when no exchange rate is available
 */
public Money convert(Money money, Currency currency) throws NoSuchExchangeRateException {

  if (money.currency == currency) {
    return money;
  }else  {
    Option<CurrencyExchangeRate> rate = directRateFor(money.currency, currency);
    if (!rate.isEmpty()) {
      return rate.get().convert(money);
    } else {
      if (allowIndirectConversions) {
        Option<CurrencyExchangeRate> crossRate = indirectRateFor(money.currency, currency);
        if (!crossRate.isEmpty()) {
          return crossRate.get().convert(money);
        } else {
          throw new NoSuchExchangeRateException(String.format("Rate for currency pair %s / %s)", money.currency, currency));
        }
      }
    }
  }
  throw new NoSuchExchangeRateException(String.format("Rate for currency pair %s / %s)", money.currency, currency)); 
}
 
开发者ID:synapplix,项目名称:jquants,代码行数:34,代码来源:MoneyContext.java

示例2: collectTestMethods

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
private static Sequence<TestMethod> collectTestMethods(Class aClass, Sequence<Method> methods) throws IOException {
    final Option<JavaClass> javaClass = getJavaClass(aClass);
    if (javaClass.isEmpty()) {
        return empty();
    }

    Map<String, List<JavaMethod>> sourceMethodsByName = getMethods(javaClass.get()).toMap(sourceMethodName());
    Map<String, List<Method>> reflectionMethodsByName = methods.toMap(reflectionMethodName());

    List<TestMethod> testMethods = new ArrayList<TestMethod>();
    TestMethodExtractor extractor = new TestMethodExtractor();
    for (String name : sourceMethodsByName.keySet()) {
        List<JavaMethod> javaMethods = sourceMethodsByName.get(name);
        List<Method> reflectionMethods = reflectionMethodsByName.get(name);
        testMethods.add(extractor.toTestMethod(aClass, javaMethods.get(0), reflectionMethods.get(0)));
        // TODO: If people overload test methods we will have to use the full name rather than the short name
    }

    Sequence<TestMethod> myTestMethods = sequence(testMethods);
    Sequence<TestMethod> parentTestMethods = collectTestMethods(aClass.getSuperclass(), methods);

    return myTestMethods.join(parentTestMethods);
}
 
开发者ID:bodar,项目名称:yatspec,代码行数:24,代码来源:TestParser.java

示例3: create

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
@POST
@Hidden
@Path("create")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> create(@FormParam("expression") Option<String> expression,
                                  @FormParam("snap") Option<String> snap) throws Exception {


    Option<String> initial = snap.isDefined()
            ? some(format(":eval %s", snapUri(snap.get())))
            : expression;

    Option<WebConsoleClientHandler> clientHandler = agent.createClient(initial);

    return clientHandler.map(clientHandlerToModel()).get()
            .insert("welcomeMessage", welcomeMessage());
}
 
开发者ID:albertlatacz,项目名称:java-repl,代码行数:18,代码来源:WebConsoleResource.java

示例4: snap

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
@POST
@Hidden
@Path("snap")
@Produces(MediaType.APPLICATION_JSON)
public Response snap(@FormParam("id") String id) {
    Option<WebConsoleClientHandler> clientHandler = agent.client(id);

    if (!clientHandler.isEmpty()) {
        String snapId = UUID.randomUUID().toString();

        Files.write(clientHandler.get().history().toString("\n").getBytes(), snapFile(snapId));

        return ok()
                .entity(emptyMap(String.class, Object.class)
                        .insert("snap", snapId)
                        .insert("uri", snapUri(snapId).toString())
                );

    } else {
        return response(BAD_REQUEST);
    }
}
 
开发者ID:albertlatacz,项目名称:java-repl,代码行数:23,代码来源:WebConsoleResource.java

示例5: modifiedResults

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
private Sequence<Result> modifiedResults(final Object expressionInstance) {
    return sequence(expressionInstance.getClass().getDeclaredFields())
            .reduceLeft(new Reducer<Field, Sequence<Result>>() {
                public Sequence<Result> call(Sequence<Result> results, Field field) throws Exception {
                    Option<Result> result = result(field.getName()).filter(where(Result::value, not(equalTo(field.get(expressionInstance)))));

                    if (result.isEmpty())
                        return results;

                    return results.append(Result.result(field.getName(), field.get(expressionInstance)));

                }

                public Sequence<Result> identity() {
                    return empty(Result.class);
                }
            });
}
 
开发者ID:albertlatacz,项目名称:java-repl,代码行数:19,代码来源:Evaluator.java

示例6: call

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
public CompletionResult call(String expression) throws Exception {
    final int lastSeparator = lastIndexOfSeparator(characters(" "), expression) + 1;
    final String packagePart = expression.substring(lastSeparator);

    Option<Pair<Class<?>, String>> completion = completionFor(packagePart);

    if (!completion.isEmpty()) {
        Function1<CompletionCandidate, String> value = CompletionCandidate::value;
        Sequence<CompletionCandidate> candidates = reflectionOf(completion.get().first())
                .declaredMembers()
                .filter(isStatic().and(isPublic()).and(not(isSynthetic())))
                .groupBy(candidateName())
                .map(candidate())
                .filter(where(value, startsWith(completion.get().second())));

        final int beginIndex = packagePart.lastIndexOf('.') + 1;
        return new CompletionResult(expression, lastSeparator + beginIndex, candidates);
    } else {
        return new CompletionResult(expression, 0, Sequences.empty(CompletionCandidate.class));
    }
}
 
开发者ID:albertlatacz,项目名称:java-repl,代码行数:22,代码来源:StaticMemberCompleter.java

示例7: parseExpression

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
private Option<Pair<String, Sequence<String>>> parseExpression(Pair<String, Sequence<String>> expression) {
    Option<Class<?>> expressionClass = evaluator.classFrom(expression.first());

    if (!expressionClass.isEmpty()) {
        return some(expression);
    }

    if (expression.first().contains(".")) {
        final String packagePart = expression.first().substring(0, expression.first().lastIndexOf("."));
        final String classPart = expression.first().substring(expression.first().lastIndexOf(".") + 1);

        return parseExpression(pair(packagePart, expression.second().cons(classPart)));
    }

    return Option.none();

}
 
开发者ID:albertlatacz,项目名称:java-repl,代码行数:18,代码来源:StaticMemberCompleter.java

示例8: main

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
public static void main(String... args) throws Exception {
    console = new ResultPrinter(printColors(args));

    ConsoleReader consoleReader = new ConsoleReader(System.in, AnsiConsole.out);
    JavaREPLClient client = clientFor(hostname(args), port(args));
    Sequence<String> initialExpressions = initialExpressionsFromFile().join(initialExpressionsFromArgs(args));
    ExpressionReader expressionReader = expressionReaderFor(consoleReader, client, initialExpressions);

    Option<String> expression = none();
    Option<EvaluationResult> result = none();
    while (expression.isEmpty() || !result.isEmpty()) {
        expression = expressionReader.readExpression();

        if (!expression.isEmpty()) {
            result = client.execute(expression.get());
            if (!result.isEmpty()) {
                for (EvaluationLog log : result.get().logs()) {
                    if (!handleTerminalCommand(log)) {
                        handleTerminalMessage(log);
                    }
                }
            }
        }
    }
}
 
开发者ID:albertlatacz,项目名称:java-repl,代码行数:26,代码来源:Main.java

示例9: execute

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
public void execute(String expression) {
    Option<String> path = parseStringCommand(expression).second();

    if (!path.isEmpty()) {
        try {
            evaluator.evaluate(Strings.lines(path.map(asFile()).get()).toString("\n"))
                    .leftOption()
                    .forEach(throwException());
            logger.success(format("Loaded source file from %s", path.get()));
        } catch (Exception e) {
            logger.error(format("Could not load source file from %s.\n  %s", path.get(), e.getLocalizedMessage()));
        }
    } else {
        logger.error(format("Path not specified"));
    }
}
 
开发者ID:albertlatacz,项目名称:java-repl,代码行数:17,代码来源:LoadSourceFile.java

示例10: optionExampleNone

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
/**
 * Here an option without a value (none):
 */
@Test
public void optionExampleNone() {
    Option<String> optionalString = none();

    assertEquals(false, optionalString.isDefined());
    try {
        optionalString.get();
        fail("This should fail as the option is not defined");
    } catch (NoSuchElementException ignored) {}
}
 
开发者ID:fleipold,项目名称:totally-lazy-tutorial,代码行数:14,代码来源:IntroductionTest.java

示例11: optionDefaultExample

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
/**
 * You can also try to get the value of an option providing
 * a default value should the option be none. This means you can avoid
 * the none check:
 *
 */
@Test
public void optionDefaultExample() {
    Option<String> optionalStringDefined = some("Hello");

    assertEquals("Hello", optionalStringDefined.getOrElse("default value"));

    Option<String> optionalStringUndefined = none();

    assertEquals("default value", optionalStringUndefined.getOrElse("default value"));
}
 
开发者ID:fleipold,项目名称:totally-lazy-tutorial,代码行数:17,代码来源:IntroductionTest.java

示例12: optionFactory

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
/** The old-school Java approach to optional values is to use `null` to indicate that
 * there is no value.
 *
 * The `option` factory method provides a way to wrap a nullable value into an option:
 *
 */
@Test
public void optionFactory() {
    Option<String> optionalStringDefined = option("Hello");
    assertEquals(some("Hello"), optionalStringDefined);

    Option<String> optionalStringUndefined = option(null);
    assertEquals(none(), optionalStringUndefined);
}
 
开发者ID:fleipold,项目名称:totally-lazy-tutorial,代码行数:15,代码来源:IntroductionTest.java

示例13: optionMapExampleNone

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
/** Here the same code passing in `none`: */
@Test
public void optionMapExampleNone() {
    Option<String> optionalString = none();

    Option<Integer> optionalNumber = optionalString.map(Integer::parseInt);
    Option<Integer> optionalDouble = optionalNumber.map(n -> 2 * n);

    assertEquals(false, optionalDouble.isDefined());
}
 
开发者ID:fleipold,项目名称:totally-lazy-tutorial,代码行数:11,代码来源:IntroductionTest.java

示例14: get

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
public UnitOfMeasure get(final String symbol) {
  if (companions.size() == 0) initQuantityCompanions();
  
  for (Dimension c : companions) {
    Option unit = c.symbolToUnit(symbol);
    if (!unit.isEmpty()) return (UnitOfMeasure) unit.get();
  }
  return null;
}
 
开发者ID:synapplix,项目名称:jquants,代码行数:10,代码来源:Dimension.java

示例15: symbolToUnit

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
public Option<UnitOfMeasure<A>> symbolToUnit(final String symbol) {
  return sequence(this.units).find(new LogicalPredicate<UnitOfMeasure>() {
    public boolean matches(UnitOfMeasure u) {
      return u.symbol.equals(symbol);
    }
  });
}
 
开发者ID:synapplix,项目名称:jquants,代码行数:8,代码来源:Dimension.java


注:本文中的com.googlecode.totallylazy.Option类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。