有没有办法用中缀符号调用scala方法(具有类型参数)
我在隐式类中有一段代码-有没有办法用中缀符号调用scala方法(具有类型参数),scala,dsl,implicit,structural-typing,Scala,Dsl,Implicit,Structural Typing,我在隐式类中有一段代码- implicit class Path(bSONValue: BSONValue) { def |<[S, T <:{def value:S}] = { bSONValue.asInstanceOf[T].value } } 问题在于没有scala会引发错误,因为它不允许使用中缀符号的类型参数方法。所以我总是要用()来包装文档/“\u id”部分。 他们使用类型参数方法时没有eg吗 doc/"_id&q
implicit class Path(bSONValue: BSONValue) {
def |<[S, T <:{def value:S}] = {
bSONValue.asInstanceOf[T].value
}
}
问题在于没有
scala会引发错误,因为它不允许使用中缀符号的类型参数方法。所以我总是要用()
来包装文档/“\u id”
部分。
他们使用类型参数方法时没有
eg吗
doc/"_id"|<[String,BSONString]
doc/“_id”|您想要从BSONValue
s中获取的所有类型T
都可能有一个同名的伴生对象。您可以使用该伴生对象作为实际想要获取的类型的直观占位符。大致如下:
trait Extract[A, BComp, B] {
def extractValue(a: A): B
}
implicit class Extractable[A](a: A) {
def |<[BC, B]
(companion: BC)
(implicit e: Extract[A, BC, B])
: B = e.extractValue(a)
}
implicit def extractIntFromString
: Extract[String, Int.type, Int] = _.toInt
implicit def extractDoubleFromString
: Extract[String, Double.type, Double] = _.toDouble
val answer = "42" |< Int
val bnswer = "42.1" |< Double
它似乎与大致相同,我建议您重新考虑API。这不仅很难阅读,而且我想你不想指定String
或BSONString
,只想指定其中一个。@LuisMiguelMejíaSuárez,好建议!
trait Extract[A, BComp, B] {
def extractValue(a: A): B
}
implicit class Extractable[A](a: A) {
def |<[BC, B]
(companion: BC)
(implicit e: Extract[A, BC, B])
: B = e.extractValue(a)
}
implicit def extractIntFromString
: Extract[String, Int.type, Int] = _.toInt
implicit def extractDoubleFromString
: Extract[String, Double.type, Double] = _.toDouble
val answer = "42" |< Int
val bnswer = "42.1" |< Double
def |<[BC, B](companion: BC)(implicit e: Extract[A, BC, B]): B
type BSONValue = String
trait Extract[B] {
def extractValue(bsonValue: BSONValue): B
}
def extract[B](bson: BSONValue)(implicit efb: Extract[B])
: B = efb.extractValue(bson)
implicit def extractIntFromString
: Extract[Int] = _.toInt
implicit def extractDoubleFromString
: Extract[Double] = _.toDouble
val answer = extract[Int]("42")
val bnswer = extract[Double]("42.1")
println(answer)
println(bnswer)