简体   繁体   English

有没有办法用中缀表示法调用scala方法(具有类型参数)

[英]Is there any way of calling scala method (having type parameter ) with infix notation

I have a piece of code in implicit class -我在隐式类中有一段代码 -

implicit class Path(bSONValue: BSONValue) {
      def |<[S, T <:{def value:S}] = {
        bSONValue.asInstanceOf[T].value
      }

} 

The problem is if I want to call |< method after BSONValue I need to call with .问题是如果我想在 BSONValue 之后调用|<方法,我需要使用. . . eg例如

(doc/"_id").|<[String,BSONString]

The problem is without .问题是没有. scala raises error because it does not allow type parameter method with infix notation. scala 引发错误,因为它不允许使用中缀表示法的类型参数方法。 So always I have to wrap doc/"_id" portion with () .所以我总是必须用()包装doc/"_id"部分。 Is their any way of using type parameter method without .他们是否可以在没有. eg例如

doc/"_id"|<[String,BSONString]

All types T that you want to get out of BSONValue s will probably have a companion object with the same name.您想要从BSONValue获取的所有类型T可能都有一个同名的伴生对象。 You could use that companion object as an intuitive placeholder for the type that you actually want to get.您可以将该伴随对象用作您实际想要获得的类型的直观占位符。 Something along these lines:沿着这些路线的东西:

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

This allows you to use infix syntax, because all those things are ordinary values.这允许您使用中缀语法,因为所有这些都是普通值。


Still, only because it's possible, it doesn't mean that you have to do it.尽管如此,仅仅因为这是可能的,并不意味着你必须这样做。 For instance, I wouldn't know what to expect from a |< -operator.例如,我不知道对|< -operator 有什么期望。 Many other people also wouldn't know what to do with it.许多其他人也不知道如何处理它。 They'd have to go and look it up.他们得去查查。 Then they would see this signature:然后他们会看到这个签名:

def |<[BC, B](companion: BC)(implicit e: Extract[A, BC, B]): B

I can imagine that the vast majority of people (myself in one week included) would not be immediately enlightened by this signature.我可以想象绝大多数人(包括我一周后)不会立即被这个签名所启发。

Maybe you could consider something more lightweight:也许你可以考虑更轻量级的东西:

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)

It seems to do roughly the same as the |< operator, but with much less magic going on.它的作用似乎与|<运算符大致相同,但使用的魔法要少得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM