com.apollographql.apollo.api.internal.Optional类的使用及代码示例

x33g5p2x  于2022-01-26 转载在 其他  
字(10.7k)|赞(0)|评价(0)|浏览(107)

本文整理了Java中com.apollographql.apollo.api.internal.Optional类的一些代码示例,展示了Optional类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Optional类的具体详情如下:
包路径:com.apollographql.apollo.api.internal.Optional
类名称:Optional

Optional介绍

[英]An immutable object that may contain a non-null reference to another object. Each instance of this type either contains a non-null reference, or contains nothing (in which case we say that the reference is "absent"); it is never said to "contain null".

A non-null Optional reference can be used as a replacement for a nullable T reference. It allows you to represent "a T that must be present" and a "a T that might be absent" as two distinct types in your program, which can aid clarity.

Some uses of this class include

  • As a method return type, as an alternative to returning null to indicate that no value was available
  • To distinguish between "unknown" (for example, not present in a map) and "known to have no value" (present in the map, with value Optional.absent())
  • To wrap nullable references for storage in a collection that does not support null (though there are several other approaches to this that should be considered first)

A common alternative to using this class is to find or create a suitable null object for the type in question.

This class is not intended as a direct analogue of any existing "option" or "maybe" construct from other programming environments, though it may bear some similarities.

Comparison to java.util.Optional (JDK 8 and higher): A new Optional class was added for Java 8. The two classes are extremely similar, but incompatible (they cannot share a common supertype). All known differences are listed either here or with the relevant methods below.

  • This class is serializable; java.util.Optional is not.
  • java.util.Optional has the additional methods ifPresent, filter, flatMap, and orElseThrow.
  • java.utiloffers the primitive-specialized versions OptionalInt, OptionalLong and OptionalDouble, the use of which is recommended; Guava does not have these.

There are no plans to deprecate this class in the foreseeable future. However, we do gently recommend that you prefer the new, standard Java class whenever possible.

See the Guava User Guide article on using Optional.
[中]可能包含对另一个对象的非空引用的不可变对象。这种类型的每个实例要么包含一个非空引用,要么不包含任何内容(在这种情况下,我们称该引用为“缺席”);它从未被称为“包含空”。
非空可选引用可以用作可空T引用的替换。它允许您将“必须存在的T”和“可能不存在的T”表示为程序中的两种不同类型,这有助于清晰。
这个类的一些用法包括
*作为方法返回类型,作为返回null以指示没有可用值的替代方法
*区分“未知”(例如,不存在于映射中)和“已知无值”(存在于映射中,值可选。缺席())
*在不支持null的集合中包装存储的可为null的引用(尽管应该首先考虑several other approaches to this
使用此类的常见替代方法是为所讨论的类型找到或创建合适的null object
这个类并不打算直接模拟其他编程环境中任何现有的“选项”或“可能”构造,尽管它可能有一些相似之处。
与java的比较。util。可选(JDK 8及更高版本):为Java8添加了一个新的可选类。这两个类非常相似,但不兼容(它们不能共享一个共同的超类型)。此处列出了所有已知差异,或使用以下相关方法列出。
*这个类是可序列化的;JAVAutil。可选项不是。
*爪哇。util。可选的还有其他方法ifPresent、filter、flatMap和orelsetrow。
*爪哇。utiloffers提供基本的专用版本Optionant、OptionalLong和OptionalDouble,建议使用这些版本;番石榴没有这些。
在可预见的未来,没有计划反对这类课程。然而,我们建议您尽可能地使用新的标准Java类。
请参阅《Guava用户指南》中关于using Optional的文章。

代码示例

代码示例来源:origin: apollographql/apollo-android

@Override public Map<Class, Map<String, Record>> dump() {
 Map<String, Record> records = new LinkedHashMap<>();
 for (Map.Entry<String, RecordJournal> entry : lruCache.asMap().entrySet()) {
  records.put(entry.getKey(), entry.getValue().snapshot);
 }
 Map<Class, Map<String, Record>> dump = new LinkedHashMap<>();
 dump.put(this.getClass(), Collections.unmodifiableMap(records));
 if (nextCache().isPresent()) {
  dump.putAll(nextCache().get().dump());
 }
 return dump;
}

代码示例来源:origin: apollographql/apollo-android

@Test
public void testOrOptionalAbsent() {
 assertEquals(Optional.of("fallback"), Optional.absent().or(Optional.of("fallback")));
}

代码示例来源:origin: apollographql/apollo-android

private void log(int priority, @NotNull String message, @Nullable Throwable t, Object... args) {
  if (logger.isPresent()) {
   logger.get().log(priority, message, Optional.fromNullable(t), args);
  }
 }
}

代码示例来源:origin: apollographql/apollo-android

public final NormalizedCacheFactory<T> chain(@NotNull NormalizedCacheFactory factory) {
  checkNotNull(factory, "factory == null");

  NormalizedCacheFactory leafFactory = this;
  while (leafFactory.nextFactory.isPresent()) {
   leafFactory = (NormalizedCacheFactory) leafFactory.nextFactory.get();
  }
  leafFactory.nextFactory = Optional.of(factory);

  return this;
 }
}

代码示例来源:origin: apollographql/apollo-android

@Override public Record call() throws Exception {
  return nextCache().flatMap(new Function<NormalizedCache, Optional<Record>>() {
   @NotNull @Override public Optional<Record> apply(@NotNull NormalizedCache cache) {
    return Optional.fromNullable(cache.loadRecord(key, cacheHeaders));
   }
  }).get(); // lruCache.get(key, callable) requires non-null.
 }
});

代码示例来源:origin: apollographql/apollo-android

public final NormalizedCache createChain(final RecordFieldJsonAdapter recordFieldAdapter) {
 if (nextFactory.isPresent()) {
  return create(recordFieldAdapter)
    .chain(nextFactory.map(new Function<NormalizedCacheFactory, NormalizedCache>() {
     @NotNull @Override public NormalizedCache apply(@NotNull NormalizedCacheFactory factory) {
      return factory.createChain(recordFieldAdapter);
     }
    }).get());
 } else {
  return create(recordFieldAdapter);
 }
}

代码示例来源:origin: apollographql/apollo-android

@Nullable @Override public Record loadRecord(@NotNull final String key, @NotNull final CacheHeaders cacheHeaders) {
 checkNotNull(key, "key == null");
 checkNotNull(cacheHeaders, "cacheHeaders == null");
 try {
  final Optional<Record> nonOptimisticRecord = nextCache()
    .flatMap(new Function<NormalizedCache, Optional<Record>>() {
     @NotNull @Override public Optional<Record> apply(@NotNull NormalizedCache cache) {
      return Optional.fromNullable(cache.loadRecord(key, cacheHeaders));
     }
    });
  final RecordJournal journal = lruCache.getIfPresent(key);
  if (journal != null) {
   return nonOptimisticRecord.map(new Function<Record, Record>() {
    @NotNull @Override public Record apply(@NotNull Record record) {
     Record result = record.clone();
     result.mergeWith(journal.snapshot);
     return result;
    }
   }).or(journal.snapshot.clone());
  } else {
   return nonOptimisticRecord.orNull();
  }
 } catch (Exception ignore) {
  return null;
 }
}

代码示例来源:origin: apollographql/apollo-android

public InterceptorResponse(okhttp3.Response httpResponse, Response parsedResponse,
   Collection<Record> cacheRecords) {
  this.httpResponse = Optional.fromNullable(httpResponse);
  this.parsedResponse = Optional.fromNullable(parsedResponse);
  this.cacheRecords = Optional.fromNullable(cacheRecords);
 }
}

代码示例来源:origin: apollographql/apollo-android

/**
 * @param record       The {@link Record} to merge.
 * @param cacheHeaders The {@link CacheHeaders} associated with the request which generated this record.
 * @return A set of record field keys that have changed. This set is returned by {@link Record#mergeWith(Record)}.
 */
@NotNull public Set<String> merge(@NotNull final Record record, @NotNull final CacheHeaders cacheHeaders) {
 checkNotNull(record, "apolloRecord == null");
 checkNotNull(cacheHeaders, "cacheHeaders == null");
 if (cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE)) {
  return Collections.emptySet();
 }
 Set<String> nextCacheChangedKeys = nextCache().map(new Function<NormalizedCache, Set<String>>() {
  @NotNull @Override public Set<String> apply(@NotNull NormalizedCache cache) {
   return cache.merge(record, cacheHeaders);
  }
 }).or(Collections.<String>emptySet());
 Set<String> currentCacheChangedKeys = performMerge(record, cacheHeaders);
 Set<String> changedKeys = new HashSet<>();
 changedKeys.addAll(nextCacheChangedKeys);
 changedKeys.addAll(currentCacheChangedKeys);
 return changedKeys;
}

代码示例来源:origin: apollographql/apollo-android

Optional<NormalizedCacheFactory> cacheFactory = this.cacheFactory;
Optional<CacheKeyResolver> cacheKeyResolver = this.cacheKeyResolver;
if (cacheFactory.isPresent() && cacheKeyResolver.isPresent()) {
 final NormalizedCache normalizedCache = cacheFactory.get().createChain(RecordFieldJsonAdapter.create());
 apolloStore = new RealApolloStore(normalizedCache, cacheKeyResolver.get(), scalarTypeAdapters, dispatcher,
   apolloLogger);
if (subscriptionTransportFactory.isPresent()) {
 subscriptionManager = new RealSubscriptionManager(scalarTypeAdapters, subscriptionTransportFactory.get(),
   subscriptionConnectionParams.or(Collections.<String, Object>emptyMap()), dispatcher,
   subscriptionHeartbeatTimeout);

代码示例来源:origin: apollographql/apollo-android

@Test
public void testGetAbsent() {
 Optional<String> optional = Optional.absent();
 try {
  optional.get();
  fail();
 } catch (IllegalStateException ignore) {
 }
}

代码示例来源:origin: apollographql/apollo-android

@Test
public void testFromNullable() {
 Optional<String> optionalName = Optional.fromNullable("bob");
 assertEquals("bob", optionalName.get());
}

代码示例来源:origin: awslabs/aws-mobile-appsync-sdk-android

@Nullable public Record loadRecord(@Nonnull final String key, @Nonnull final CacheHeaders cacheHeaders) {
 return selectRecordForKey(key)
   .apply(new Action<Record>() {
    @Override
    public void apply(@Nonnull Record record) {
     if (cacheHeaders.hasHeader(EVICT_AFTER_READ)) {
      deleteRecord(key);
     }
    }
   })
   .or(nextCache().flatMap(new Function<NormalizedCache, Optional<Record>>() {
    @Nonnull @Override
    public Optional<Record> apply(@Nonnull NormalizedCache cache) {
     return Optional.fromNullable(cache.loadRecord(key, cacheHeaders));
    }
   }))
   .orNull();
}

代码示例来源:origin: apollographql/apollo-android

@Test
public void testFlatMapAbsent() {
 assertEquals(Optional.absent(), Optional.absent().flatMap(new Function<Object, Optional<String>>() {
  @NotNull @Override public Optional<String> apply(@NotNull Object o) {
   return Optional.of(o.toString());
  }
 }));
}

代码示例来源:origin: apollographql/apollo-android

@Test
public void testMapAbssentFunctionReturnsNull() {
 assertEquals(Optional.absent(),
   Optional.absent().map(
     new Function<Object, Object>() {
      @Override public Object apply(Object input) {
       return null;
      }
     }));
}

代码示例来源:origin: apollographql/apollo-android

@Test
public void testFromNullableNull() {
 // not promised by spec, but easier to test
 assertSame(Optional.absent(), Optional.fromNullable(null));
}

代码示例来源:origin: apollographql/apollo-android

@Test
public void testAbsent() {
 Optional<String> optionalName = Optional.absent();
 assertFalse(optionalName.isPresent());
}

代码示例来源:origin: apollographql/apollo-android

@Test
public void testEqualsAndHashCodePresent() {
 assertEquals(Optional.of("training"), Optional.of("training"));
 assertFalse(Optional.of("a").equals(Optional.of("b")));
 assertFalse(Optional.of("a").equals(Optional.absent()));
 assertEquals(Optional.of("training").hashCode(), Optional.of("training").hashCode());
}

代码示例来源:origin: apollographql/apollo-android

@SuppressWarnings("unused") // compilation test
@Test
public void testSampleCodeFine1() {
 Optional<Number> optionalInt = Optional.of((Number) 1);
 Number value = optionalInt.or(0.5); // fine
}

代码示例来源:origin: apollographql/apollo-android

@Test
public void testFlatMapMapPresentIdentity() {
 assertEquals(Optional.of("a"), Optional.of("a").flatMap(new Function<String, Optional<String>>() {
    @NotNull @Override public Optional<String> apply(@NotNull String s) {
     return Optional.of(s);
    }
   })
 );
}

相关文章