微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Scala 3 / Dotty中的依赖元组

如何解决Scala 3 / Dotty中的依赖元组

我正在尝试使用一系列依赖元组一个依赖映射进行编码。 这是我无法使用的内容

  class DTuple[Key,ValueMap[_ <: Key]](val first: Key)(val second: ValueMap[first.type])
  
  type DKey = "Tag" | "Versions" | "Author"

  type DMapping[X <: DKey] = X match {
      case "Tag" => String
      case "Versions" => Array[String]
      case "Author" => String
    }
  
  def mkString(d: DTuple[DKey,DMapping]) = d.first match {
    case _: "Tag" => "#" + d.second
    case _: "Versions" => d.second.mkString(",")
    case _: "Author" => "@" + d.second
  }

我所能得到的

[error] -- [E008] Not Found Error: Main.scala:21:35
[error] 21 |    case _: "Versions" => d.second.mkString(",")
[error]    |                          ^^^^^^^^^^^^^^^^^
[error]    |      value mkString is not a member of Main.DMapping[(d.first : Main.DKey)]

我想不出一种模式匹配d.second的好方法,因此其类型取决于d.first。我可以添加.asInstanceOf[Array[String]].asInstanceOf[String],但这不是这里的目标,我正在尝试对代码进行类型检查。

解决方法

也许有更好,更轻松的方法来做到这一点,但是:

import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME

// This is a case case solely for the unapply method,you could implement it on your own
case class DTuple[Key,ValueMap[_ <: Key]](first: Key)(val second: ValueMap[first.type])

type DKey = "Tag" | "Versions" | "Author" | "BuildTime"

type DMapping[X <: DKey] = X match {
  case "Tag" => String
  case "Versions" => Array[String]
  case "Author" => String
  case "BuildTime" => ZonedDateTime
}

// the DTuple("<value>") is used at runtime to check the string (DKey) value
// the DTuple["<value>",DMapping] type hint makes dotty see the `d` value as the correct type,hence infering the type of d.second too
def mkString(dt: DTuple[DKey,DMapping]): String = dt match {
  // this would fail at runtime as e.g DTuple("Tag") would enter this case (the `DTuple["BuildTime",DMapping]` is unchecked at runtime
  // case d: DTuple["BuildTime",DMapping] => d.second.format(ISO_ZONED_DATE_TIME)

  // this doesn't compile because `d.second`'s type is still 'DMapping[(d.first : DKey)]',not 'DMapping["BuildTime"]'
  // case d@DTuple("BuildTime") => d.second.format(ISO_ZONED_DATE_TIME)

  case d@DTuple("Tag"): DTuple["Tag",DMapping] => d.second
  case d@DTuple("Versions"): DTuple["Versions",DMapping] => d.second.mkString(",")
  case d@DTuple("Author"): DTuple["Author",DMapping] => d.second.toString
  case d@DTuple("BuildTime"): DTuple["BuildTime",DMapping] => d.second.format(ISO_ZONED_DATE_TIME)
}

object Main extends App {
  List(
    DTuple[DKey,DMapping]("Versions")(Array("1.0","2.0")),DTuple[DKey,DMapping]("Tag")("env=SO"),DMapping]("Author")("MK"),DMapping]("BuildTime")(ZonedDateTime.now())
  ).foreach { dt =>
    println(mkString(dt))
  }
}

打印

1.0,2.0
env=SO
MK
2020-10-23T21:04:06.696+02:00[Europe/Paris]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。