使通用类型可用的隐式转换
Implicit conversion to make generic type available
我正在使用一个具有 class 的库,该库具有可能非常复杂的通用类型。我需要编写一个方法,该方法采用库 class 的 val 具有的泛型类型的参数,并且我想避免必须在方法签名中写出类型。我想我可以创建一个隐式的 class ,它将一个类型添加到我可以在方法签名中使用的 val ,有点像:
// This comes from a library and can't be changed
case class LibraryClass[A](a: A)
//----------------------------------
object MyCode {
val thing = LibraryClass(3)
implicit class LibraryClassWithType[A](lc: LibraryClass[A]) {
type TheType = A
}
def doStuff(something: thing.TheType): Unit = {
println(something)
}
}
这不会编译(TheType 不是 LibraryClass 的成员)。但是,如果我自己将它包装在 class 中,它就可以工作
val thingWithType = LibraryClassWithType(thing)
def doStuff(something: thingWithType.TheType): Unit = {
println(something)
}
我是否遗漏了一些可以使这项工作正常进行的东西,或者这种隐式转换是否对 Scala 无效?
你可以像这样做(我认为)你想做的事:
implicit val thing = LibraryClass(3)
def doStuff[A](something: A)(implicit lc: LibraryClass[A])
我不明白的是为什么这需要这么复杂。例如,为什么不坚持你的第二种方法,没有隐含的,有效的,或者为什么不这样做
def doStuff[A](something: A)
开始?
我无法用隐式做这种事情,但我不得不做类似的事情,我刚刚实例化了这些类型的持有者:
case class LibraryClass[A](a: A)
object MyCode {
val thing = LibraryClass(3)
class HigherTypeHolder[A,F[A]](a: F[A]) {
type AT = A
}
val th = new HigherTypeHolder(thing)
def doStuff(something: th.AT): Unit = {
println(something)
}
}
我正在使用一个具有 class 的库,该库具有可能非常复杂的通用类型。我需要编写一个方法,该方法采用库 class 的 val 具有的泛型类型的参数,并且我想避免必须在方法签名中写出类型。我想我可以创建一个隐式的 class ,它将一个类型添加到我可以在方法签名中使用的 val ,有点像:
// This comes from a library and can't be changed
case class LibraryClass[A](a: A)
//----------------------------------
object MyCode {
val thing = LibraryClass(3)
implicit class LibraryClassWithType[A](lc: LibraryClass[A]) {
type TheType = A
}
def doStuff(something: thing.TheType): Unit = {
println(something)
}
}
这不会编译(TheType 不是 LibraryClass 的成员)。但是,如果我自己将它包装在 class 中,它就可以工作
val thingWithType = LibraryClassWithType(thing)
def doStuff(something: thingWithType.TheType): Unit = {
println(something)
}
我是否遗漏了一些可以使这项工作正常进行的东西,或者这种隐式转换是否对 Scala 无效?
你可以像这样做(我认为)你想做的事:
implicit val thing = LibraryClass(3)
def doStuff[A](something: A)(implicit lc: LibraryClass[A])
我不明白的是为什么这需要这么复杂。例如,为什么不坚持你的第二种方法,没有隐含的,有效的,或者为什么不这样做
def doStuff[A](something: A)
开始?
我无法用隐式做这种事情,但我不得不做类似的事情,我刚刚实例化了这些类型的持有者:
case class LibraryClass[A](a: A)
object MyCode {
val thing = LibraryClass(3)
class HigherTypeHolder[A,F[A]](a: F[A]) {
type AT = A
}
val th = new HigherTypeHolder(thing)
def doStuff(something: th.AT): Unit = {
println(something)
}
}