• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java Option类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: parseString

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
public Option<A> parseString(String s) {
   String pattern = "([-+]?[0-9]*\\.?[0-9]+) *(" + sequence(units).toString("|") + ")$";
Regex regex = regex(pattern);
   if (regex.matches(s)) {
     MatchResult match = regex.match(s);
     Option<UnitOfMeasure<A>> unit = symbolToUnit(match.group(2));
     double value = new Double(match.group(1)).doubleValue();
     return some(unit.get().apply(value));
   } else {
     throw new QuantityStringParseException("Unable to parse " + name + " " + s);
   }
 }
 
开发者ID:synapplix,项目名称:jquants,代码行数:13,代码来源:Dimension.java


示例17: directRateFor

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
/**
 * Returns an Option on an exchange rate if a direct rate exists, otherwise None
 *
 * @param curA Currency A
 * @param curB Currency B
 * @return
 */
public Option<CurrencyExchangeRate> directRateFor(final Currency curA, final Currency curB ) {
  Option<CurrencyExchangeRate> find = sequence(rates).find(new Predicate<CurrencyExchangeRate>() {
    public boolean matches(CurrencyExchangeRate r) {
      return (r.base.currency == curA && r.counter.currency == curB || r.base.currency == curB && r.counter.currency == curA);
    }
  });
  return find;
}
 
开发者ID:synapplix,项目名称:jquants,代码行数:16,代码来源:MoneyContext.java


示例18: indirectRateFor

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
/**
 * Return an Option on an exchange rate.  If a direct rate exists an Option on that will be returned.
 * Otherwise, if a cross rate can be determined (1 hop limit), it will be created and returned in an Option.
 * Otherwise, None will be returned
 *
 * @param curA Currency A
 * @param curB Currency B
 * @return
 * @throws NoSuchExchangeRateException 
 */
public Option<CurrencyExchangeRate> indirectRateFor(final Currency curA, final Currency curB) throws NoSuchExchangeRateException {

  // TODO Improve this to attempt to use defaultCurrency first
  Option<CurrencyExchangeRate> directRateFor = directRateFor(curA, curB);
  if (!directRateFor.isEmpty()) {
    return directRateFor;
  } else {
    List<CurrencyExchangeRate> ratesWithCurA = new ArrayList<CurrencyExchangeRate>();
    List<CurrencyExchangeRate> ratesWithCurB = new ArrayList<CurrencyExchangeRate>();
    for (CurrencyExchangeRate r : this.rates) {
      if (r.base.currency == curA || r.counter.currency == curA) {
        ratesWithCurA.add(r);
      }
      if (r.base.currency == curB || r.counter.currency == curB) {
        ratesWithCurB.add(r);
      }
    }
    List<Currency> curs = new ArrayList<Currency>();
    for (Currency cur : this.currencies) {
      if ((containsBaseCurrency(ratesWithCurA, cur) || containsCounterCurrency(ratesWithCurA, cur)) && 
          (containsBaseCurrency(ratesWithCurB, cur) || containsCounterCurrency(ratesWithCurB, cur))) {
        curs.add(cur);
      }
    }
    if (curs.size() > 0) {
      Money m = Money(1d, curs.get(0));
      return Some.some(new CurrencyExchangeRate(convert(m, curA), convert(m, curB)));
    } else {
      return None.none();
    }
  }
}
 
开发者ID:synapplix,项目名称:jquants,代码行数:43,代码来源:MoneyContext.java


示例19: encodeUrl

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
private static Option<String> encodeUrl(CharSequence term) {
    try {
        return Option.some(URLEncoder.encode(term.toString(), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        return Option.none();
    }
}
 
开发者ID:blomqvie,项目名称:android-rxjava-training,代码行数:8,代码来源:AppObservables.java


示例20: lookup

import com.googlecode.totallylazy.Option; //导入依赖的package包/类
@Override
public List lookup(Term key) {
    Option<Term> result = set.lookup(key);
    if (result.isEmpty()) {
        return List.nil;
    } else {
        return List.of(result.get());
    }
}
 
开发者ID:jerlang,项目名称:jerlang,代码行数:10,代码来源:Set.java



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java NonAnonymousResponseProcessor类代码示例发布时间:2022-05-22
下一篇:
Java IClassHierarchy类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap