Scala/Play 的语法和含义!代码示例 [英] Syntax and meaning of a Scala/Play! code sample

查看:19
本文介绍了Scala/Play 的语法和含义!代码示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Scala/Play! 代码:

case class Tweet(from: String, text: String)

implicit val tweetReads = (
 (JsPath  "from_user_name").read[String] ~
 (JsPath  "text").read[String]) (Tweet.apply _)

我有几个关于上述代码的语法和含义的问题:

  • 在哪个类/对象上调用 ~ 方法?
  • 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"

方法 readJsPath

val reads1: Reads[String] = path1.read[String]
val reads2: Reads[String] = path2.read[String]

Reads中没有方法~,但是FunctionalBuilderOps中有这样的方法,并且有一个来自M的隐式转换[T]FunctionalBuilderOps[M[_], T]play.api.libs.functional.syntax - 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#readtoFunctionalBuilderOpsCanBuild2#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 的语法和含义!代码示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆