【问题标题】:Is there any way of calling scala method (having type parameter ) with infix notation有没有办法用中缀表示法调用 scala 方法(具有类型参数)
【发布时间】:2021-01-16 09:54:12
【问题描述】:

我在隐式类中有一段代码-

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

} 

问题是如果我想在 BSONValue 之后调用 |&lt; 方法,我需要使用 . 调用。 例如

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

问题是没有. scala 会引发错误,因为它不允许使用中缀表示法的类型参数方法。所以我总是必须用() 包裹doc/"_id" 部分。 他们是否可以在没有. 的情况下使用类型参数方法,例如

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

【问题讨论】:

  • 我建议您重新考虑您的 API。它不仅难以阅读,而且我猜您不想指定StringBSONString,而只想指定其中之一。
  • @LuisMiguelMejíaSuárez,好建议!

标签: scala dsl implicit structural-typing


【解决方案1】:

您想从BSONValues 中删除的所有类型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

这允许您使用中缀语法,因为所有这些都是普通值。


不过,仅仅因为它是可能的,并不意味着你必须这样做。 例如,我不知道对|&lt;-operator 有什么期望。 许多其他人也不知道如何处理它。 他们必须去查一下。然后他们会看到这个签名:

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)

它的作用似乎与|&lt; 运算符大致相同,但作用要小得多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多