[英]Defining Reads for java.util.Set with `_`
Using the Play Framework's JSON library, I'm trying to define a Reads[Obj]
for: 我正在尝试使用Play Framework的JSON库为以下项定义Reads[Obj]
:
Obj.java Obj.java
public class Obj {
private Long id;
private String description;
private Set<Group> groups;
public Obj(Long id, String description, Set<Group> groups) {
// set fields
}
}
However, when I use _.asJava
, I get missing parameter type
compile-time error. 但是,当我使用_.asJava
,会missing parameter type
编译时错误。
import play.api.libs.json._
import play.api.libs.functional.syntax._
import scala.collection.JavaConverters._
implicit val ObjReads: Reads[Obj] = (
(JsPath \ "id").read[Long] and
(JsPath \ "description").read[String] and
(JsPath \ "groups").read[Set[Group]] and
)(new Obj(_,_,_.asJava))
Note that I need to call asJava
to convert from scala.collection.immutable.Set
to java.util.Set
. 请注意,我需要调用asJava
从scala.collection.immutable.Set
转换为java.util.Set
。
Without naming each parameter and its type, how can I succinctly call asJava
on the third element? 在不命名每个参数及其类型的情况下,如何在第三个元素上简洁地调用asJava
?
You can't always always just throw in underscores instead of names because the compiler doesn't always know how you want to resolve them. 您不能总是总是仅使用下划线而不是名称,因为编译器并不总是知道如何解析它们。
def f(a: String, b: String) = f"$a~$b"
Vector(1,2,3).foldLeft("0")(f(_, _.toString)) // ERROR
Vector(1,2,3).foldLeft("0")((z,x) => f(z, x.toString)) // fine
Just giving names to the parameters is an easy way to fix it. 仅给参数命名是修复它的简便方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.