问题描述
我正在使用ADT和Aux-pattern设计类型安全的代码,无法摆脱某些asInstanceOf
。这是示例:
sealed trait Source
case object FileSystem extends Source
case object Network extends Source
sealed trait Data {
type S <: Source
}
object Data {
type Aux[T <: Source] = Data { type S = T }
}
case class RegularFile(path: String) extends Data { type S = FileSystem.type }
case class Directory(path: String) extends Data { type S = FileSystem.type }
case class UnixDevice(path: String) extends Data { type S = FileSystem.type }
case class Remote(ip: String) extends Data { type S = Network.type }
//Lots of asInstanceOf
def availableData[S <: Source](src: Source): List[Data.Aux[S]] = {
src match {
case FileSystem => List(
RegularFile("/tmp/test").asInstanceOf[Data.Aux[S]],Directory("/home/somename").asInstanceOf[Data.Aux[S]],UnixDevice("/dev/null").asInstanceOf[Data.Aux[S]],)
case Network => List(
Remote("192.168.0.1").asInstanceOf[Data.Aux[S]]
)
}
}
在这种情况下,很明显asInstanceOf
是正确的,但是有没有办法操纵它?
我当时正在考虑S <: Source: classtag
,但在这里似乎没有用。也许还有其他反思技巧?
解决方法
请参阅说明为什么签名
def availableData[S <: Source](src: S): List[Data.Aux[S]] = {
src match {
case FileSystem => List(
RegularFile("/tmp/test"),Directory("/home/somename"),UnixDevice("/dev/null"),)
case Network => List(
Remote("192.168.0.1")
)
}
}
不起作用,有几种解决方法:
Generic function where the return type depends on the input type in Scala?
Type mismatch on abstract type used in pattern matching
例如,尝试类型类
trait AvailableData[S <: Source] {
def availableData(src: S): List[Data.Aux[S]]
}
object AvailableData {
implicit val fileSystem: AvailableData[FileSystem.type] = _ =>
List[Data.Aux[FileSystem.type]](
RegularFile("/tmp/test"),)
implicit val network: AvailableData[Network.type] = _ =>
List[Data.Aux[Network.type]](
Remote("192.168.0.1")
)
}
def availableData[S <: Source](src: S)(implicit
ad: AvailableData[S]
): List[Data.Aux[S]] = ad.availableData(src)