问题描述
我有以下 Scala/Play!代码:
case class Tweet(from: String, text: String)
implicit val tweetReads = (
(JsPath \ "from_user_name").read[String] ~
(JsPath \ "text").read[String]) (Tweet.apply _)
关于上述代码的语法和含义,我有几个问题:
I have several questions regarding the syntax and meaning of the above code:
-
~
方法在什么类/对象上调用? -
Tweet.apply
的参数的类/类型是什么?
- On what class/object is the
~
method invoked on? - What is the class/type of the argument to
Tweet.apply
?
编辑1 :完整的源代码:
package models
import play.api.libs.json._
import play.api.libs.json.util._
import play.api.libs.json.Reads._
import play.api.libs.json.Writes._
import play.api.libs.functional.syntax._
case class Tweet(from: String, text: String)
object Tweet {
implicit val tweetReads = (
(JsPath \ "from_user_name").read[String] ~
(JsPath \ "text").read[String])(Tweet.apply _)
implicit val tweetWrites = (
(JsPath \ "from").write[String] ~
(JsPath \ "text").write[String])(unlift(Tweet.unapply))
}
推荐答案
分步操作:
对象JsPath上的方法\
Method \
on object JsPath
val path1: JsPath = JsPath \ "from_user_name"
val path2: JsPath = JsPath \ "text"
类型为JsPath
val reads1: Reads[String] = path1.read[String]
val reads2: Reads[String] = path2.read[String]
在Reads
中没有方法~
,但是在FunctionalBuilderOps
中存在这样的方法,并且在-toFunctionalBuilderOps
.
There is no method ~
in Reads
, but there is such method in FunctionalBuilderOps
and there is an implicit conversion from M[T]
to FunctionalBuilderOps[M[_], T]
in play.api.libs.functional.syntax
- toFunctionalBuilderOps
.
val reads1FunctionalBuilderOps: FunctionalBuilderOps[Reads, String] =
toFunctionalBuilderOps(reads1)
val canBuild2: CanBuild2[String, String] = reads1FunctionalBuilderOps.~(reads2)
Tweet.apply _
是使用带有N
参数的方法创建FunctionN
的scala语法:
Tweet.apply _
is a scala syntax to create a FunctionN
using method with N
arguments:
val func: (String, String) => Tweet = Tweet.apply _
在CanBuild2[A, B]
中有一个apply
方法.它接受(A, B) => C
并返回Reads[C]
(在这种情况下):
There is an apply
method in CanBuild2[A, B]
. It accepts (A, B) => C
and returns Reads[C]
(in this case):
implicit val tweetReads: Reads[Tweet] = canBuild2.apply(func)
实际上,在JsPath#read
,toFunctionalBuilderOps
和CanBuild2#apply
方法中也存在隐式参数.使用该参数:
Actually there are also implicit parameters in JsPath#read
, toFunctionalBuilderOps
and CanBuild2#apply
methods. With that parameters:
val reads1: Reads[String] = path1.read[String](Reads.StringReads)
...
val reads1FunctionalBuilderOps: FunctionalBuilderOps[Reads, String] =
toFunctionalBuilderOps(reads1)(
functionalCanBuildApplicative(
Reads.applicative(JsResult.applicativeJsResult)))
...
implicit val tweetReads: Reads[Tweet] =
canBuild2.apply(func)(functorReads)
这篇关于Scala/Play的语法和含义!代码样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!