gpt4 book ai didi

scala - Scala/Play 的语法和含义!代码示例

转载 作者:行者123 更新时间:2023-12-04 22:18:31 25 4
gpt4 key购买 nike

我有以下 斯卡拉/玩! 代码:

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

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

我有 关于上述代码的语法和含义的几个问题 :
  • ~ 在哪个类/对象上方法调用?
  • 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 上

    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 .
    val reads1FunctionalBuilderOps: FunctionalBuilderOps[Reads, String] =
    toFunctionalBuilderOps(reads1)

    val canBuild2: CanBuild2[String, String] = reads1FunctionalBuilderOps.~(reads2)
    Tweet.apply _是用于创建 FunctionN 的 Scala 语法使用方法与 N论据:
    val func: (String, String) => Tweet = Tweet.apply _

    有一个 apply CanBuild2[A, B] 中的方法.它接受 (A, B) => C并返回 Reads[C] (在这种情况下):
    implicit val tweetReads: Reads[Tweet] = canBuild2.apply(func)

    其实 JsPath#read中也有隐式参数, toFunctionalBuilderOpsCanBuild2#apply方法。使用该参数:
    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 - Scala/Play 的语法和含义!代码示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20990812/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com