【发布时间】:2015-01-17 11:01:19
【问题描述】:
我需要一些帮助来尝试弄清楚如何重用我不想重复的模式匹配(如果可能的话)。我在这里和谷歌搜索过,尝试了隐式和方差,但到目前为止没有结果。
下面是 2 个方法,doSomething 和 doSomethingElse,它们在 Id 上包含相同的模式匹配。我想通过传入一个函数来重用该模式。
这是初始设置。 (toPath 和 take2 的实际实现并不真正相关。)
import java.nio.file.{Paths, Path}
import java.util.UUID
def take2(x: Long): String = {
(x % 100).toString.padTo(2, '0')
}
def take2(u: UUID): String = {
u.toString.take(2)
}
def toPath(x: Long): Path = {
Paths.get(s"$x")
}
def toPath(u: UUID): Path = {
Paths.get(u.toString)
}
case class Ids(id1: Option[Long], id2: Option[UUID])
def doSomething(ids: Ids): String = ids match {
case Ids(_, Some(uuid)) => take2(uuid)
case Ids(Some(long), _) => take2(long)
}
def doSomethingElse(ids: Ids) = ids match {
case Ids(_, Some(uuid)) => toPath(uuid)
case Ids(Some(long), _) => toPath(long)
}
doSomething(Ids(Some(12345L), None))
doSomethingElse(Ids(Some(12345L), None))
我想要这样的东西起作用:
def execute[A](ids: Ids)(f: Any => A): A = ids match {
case Ids(_, Some(uuid)) => f(uuid)
case Ids(Some(long), _) => f(long)
}
def _doSomething(ids: Ids) = execute[String](ids)(take2)
//def _doSomething2(ids: Ids) = execute[Path](ids)(toPath)
我得到的错误是:
Error: ... type mismatch;
found : (u: java.util.UUID)String <and> (x: Long)String
required: Any => String
def _doSomething(ids: Ids) = execute[String](ids)(take2)
^ ^
请问我怎样才能使这些函数类型工作?
我的 Scala 版本 2.11.2。
感谢任何帮助或指点。
【问题讨论】:
标签: scala types type-conversion pattern-matching