我正在阅读Swift文档,并挂断了我认为文档不一致的内容.
在if语句中,条件必须是布尔表达式 - 这意味着诸如得分{...}之类的代码是错误,而不是与零的隐式比较.
因此严格的"布尔"将为TRUE或FALSE.
您可以使用if和let一起使用可能缺少的值.这些值表示为选项.可选值包含值或包含nil以指示缺少值.在值的类型后面写一个问号(?)以将值标记为可选
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
Run Code Online (Sandbox Code Playgroud)
如果可选值为nil,则条件为false
因此,通过"布尔",它们似乎意味着"truthy/falsy",因为nil隐含地意味着错误
并跳过括号中的代码.否则,将解包可选值并在let之后将其分配给常量,这使得在代码块内可用的展开值.
所以这里是我看到不一致的地方.在上面的代码示例中,由于optionalName具有值,因此该name变量被赋值为"John Appleseed".
因此,在比较中,我们最终得到了非布尔的表达 ; 特别是,"John Appleseed." 这是"真实的",但不是布尔值,这与第1点相矛盾!
换句话说 - 在代码中 - 在let中赋值后,我们有:
if "John Appleseed" {
greeting = "Hello, \(name)"
} …Run Code Online (Sandbox Code Playgroud) 在Class中Site,我有两种实用方法.
第一个,如果没有错误发生parseStub,则解析Site为a ; 否则,它返回.使用:Master nullOptional
public static Optional<Master> parseStub(Site site) {
// do some parse work; return Optional.empty() if the parse fails.
}
Run Code Online (Sandbox Code Playgroud)
第二种方法parseStubs是解析的列表Site到的列表Master.它重用parseStub,并且必须处理可能为空的Optional<Master>:
public static List<Master> parseStubs(List<Site> sites) {
return sites.stream()
.<Master>map(site -> Site.parseStub(site).orElse(null))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
请注意,在上面的代码中,我
null再次介绍.
我怎么能避免null(和filter(Objects::nonNull))使用Optional一致?
我最近在Scala遇到了一个令人困惑的问题.我希望得到以下代码None,但结果是Some(null):
Option("a").map(_ => null)
Run Code Online (Sandbox Code Playgroud)
这背后的原因是什么?为什么不导致None?
注意:这个问题不是为什么有些(null)不被视为无重复?,因为问题要求明确使用Some(null).我的问题是关于使用Option.map.
我有一个F#record type(Request<'a>)定义了一个字段作为('a -> bool) option.在某些时候,我有一个这种记录类型的数组,并希望对它进行排序,以便所有的那些Some ('a -> bool)都是第一个(最低索引),并且所有那些None将是最后一个(最高索引).
我尝试过以下操作,但这似乎不起作用,因为我有一些位于数组的中间/末尾:
let sort (req1:Request<'a>) (req2:Request<'a>) =
if req1.ResourceCondition.IsSome
then
-1
else if req2.ResourceCondition.IsSome
then
1
else
0
let reqArray = Array.sortWith sort fifoArray
Run Code Online (Sandbox Code Playgroud) 您能举一个例子,说明如何使用Java 8 Optional来转换它.
Motion motion = new Motion();
if (null!= site.getLocation() && null != site.getLocation().getLatitude() && null != site.getLocation().getLongitude()) {
Point p = GeoJson.point(site.getLocation().getLatitude(), site.getLocation().getLongitude());
motion.setLocation(p);
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我这样做
Motion motion = new Motion();
Optional<Location> locationOptional = Optional.ofNullable(site.getLocation());
Point p = locationOptional
.map(location -> {
if (Optional.ofNullable(location.getLatitude()).isPresent() && Optional.ofNullable(location.getLongitude()).isPresent()) {
return GeoJson.point(location.getLatitude(), location.getLongitude());
}
return null;
})
.orElse(null);
motion.setLocation(p);
Run Code Online (Sandbox Code Playgroud) 对对象使用“空检查”选项克隆不同类型的对象。
class A{ C cObj, List<B> bList;}
class B{ C cObj; List<C> cList;}
class C { String label; String value;}
class D{ String name; String age; String addressCode;}
Run Code Online (Sandbox Code Playgroud)
映射A-> D
d.setAddessCode(A.getBlist().get(0).getcList().get(0).getValue());
Run Code Online (Sandbox Code Playgroud)
如何使用Java 8可选检查null
A.getBlist().get(0).getcList().get(0).getValue()
Run Code Online (Sandbox Code Playgroud)
我试过了
d.setAddessCode(Optional.ofNullable(A).map(A::getBList).map(Stream::of).orElseGet(Stream::empty).findFirst().map(B::getCList).map(Stream::of).orElseGet(Stream::empty).findFirst().map(C::getValue).orElse(null)));
Run Code Online (Sandbox Code Playgroud)
我如何才能一起检查列表和值中的null。
什么是惯用的,最小的(也许是功能性的)方式来说Optional<String>和说,
true如果为null或空,或query_str = <str>否则.当然,这是我笨重的尝试:
Optional<String> queryMaybe; // Given.
String clause = "true";
if (queryMaybe.isPresent() && !queryMaybe.get().isEmpty()) {
clause = "query_str = " + queryMaybe.get();
}
Run Code Online (Sandbox Code Playgroud)
但是我的同事们编写的周围代码似乎使用了很多,我认为可能被称为"功能"样式链接.例如,
String externalTraffickedStateClauses = StringUtils.defaultIfBlank(
externalTraffickedStateQueries.stream().collect(Collectors.joining(" OR ")), "false");
Run Code Online (Sandbox Code Playgroud)
和
SORTORDERBY orderBy = orderByMaybe.orElse(DEFAULT_ORDER_BY);
Run Code Online (Sandbox Code Playgroud)
所以,我想,以符合自己的风格,就像我能,即链stream,filter,orElse等不知道这是因为我从C++背景的还是因为我的学习收获是已经过时,但是这仍然是很对我不熟悉
我正在尝试学习如何Optional在Java中使用- 但这似乎不正确我在做什么.
User user = null;
public AuthCheck(User user) throws Exception {
if (user == null) {
throw new Exception("No user!");
}
if (!(user.getStuff() != null && !user.getStuff().isEmpty())) {
throw new Exception("User has no stuff");
}
this.user = user;
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试使用Optional以下方法转换它:
Optional<UserOptional> user;
public AuthCheckOptional(Optional<UserOptional> user) throws Exception {
user.orElseThrow(() -> new Exception("No User!"));
user.map(UserOptional::getStuff)
.orElseThrow(() -> new Exception("User has no stuff"));
this.user = user;
}
Run Code Online (Sandbox Code Playgroud)
我想我不需要两次单独检查.另外我相信我已经改变了逻辑,因为IsEmpty()没有发生.
我们有一种方法,其中我们接收一个Optional<SomeType>对象.如果包含的SomeType对象不为null,那么我们必须SomeOtherType使用对象的字段初始化SomeType对象并返回该新对象; 否则我们必须返回null
我们找到了多个不同的解决方案,我们用两个语句执行此任务,首先检索可选对象,然后再创建另一个类型对象,例如
private SomeOtherType ourMethod() {
SomeType someObject = getOptionalSomeTypeFromSomeWhere().orElse(null);
return someObject != null ? new SomeOtherType(someObject.getField1(), someObject.getField2(), ...) : null;
}
Run Code Online (Sandbox Code Playgroud)
有可能用一个陈述来涵盖这个吗?到目前为止,我们无法进行空检查,访问字段,创建新对象等
基本上这个问题的一个更复杂的情况:获取可选对象的字段或返回null
我有一个要求,对于具有大约30+个给定案例类的Option [T]字段,必须至少具有1个字段nonEmpty才有效。我没有单独检查每个字段,而是选择了以通用方式通过反射检查所有字段。我想出的代码(也基于SO中的其他答案)是:
import scala.reflect.runtime.universe._
import scala.reflect.runtime.{universe => ru}
// gets all methods of a Case Class
def getMethods[T: ru.TypeTag] = typeOf[T].members.collect {
case m: MethodSymbol if m.isCaseAccessor => m
}.toList
/**
* Returns the value of all Case Class fields
* @param obj case class object
* @return a Sequence of all field values
*/
def getAllCaseClassFieldValues[T: ru.TypeTag](obj: Object): Seq[Any] = {
val mirror = ru.runtimeMirror(getClass.getClassLoader)
getMethods[T].map(m => mirror.reflect(obj).reflectField(m).get)
}
Run Code Online (Sandbox Code Playgroud)
案例类:
case class SampleRequest(field1: Option[String], field2: Option[String], //.... up to …Run Code Online (Sandbox Code Playgroud) optional ×10
java-8 ×5
java ×4
java-stream ×2
scala ×2
.net ×1
arrays ×1
case-class ×1
coding-style ×1
conditional ×1
f# ×1
lambda ×1
let ×1
nullable ×1
object ×1
reflection ×1
sorting ×1
swift ×1
validation ×1
xcode6 ×1