【问题标题】:What do Multiple parameter lists to Some() in scala achieve?scala 中 Some() 的多个参数列表实现了什么?
【发布时间】:2020-04-19 04:09:21
【问题描述】:

谁能向我解释一下下面 Some() 类的多个参数列表实现了什么?

我在阅读与使用 ClassTags 相关的解决方案时遇到了这个问题:

Implicit parameter and ClassTag

object Other { 
  def apply[T: ClassTag](data: T)(implicit ordering: Ordering[T]): T =
    Some(data)(implicitly, ordering.reverse)
}

【问题讨论】:

  • 您到底想问什么?你是问类型参数T还是什么问题不清楚。
  • 根据您的更新,一切都很清楚。 Some 不是 Option 中的一个,而是一个在其第二个参数列表中接收这两个隐式的新类。那么现在,问题是什么?这段代码没有任何问题,只是显式传递了两个隐式参数。

标签: scala scala-collections


【解决方案1】:

正如引用问题的答案所述,您可以这样写Some.apply

def apply[T](data: T)(implicit evidence: ClassTag[T], ordering: Ordering[T]): T = data

或者对两者都使用Context Bounds(语法糖),例如:

def apply[T: ClassTag: Ordering](data: T): T = data

因此在Other 中,它使用显式参数调用Some.apply(它改变了顺序)。

由于隐式参数只允许一个参数列表,因此您还必须显式添加ClassTag参数。

您可以通过implicitly 实现此目的。

还要查看文档:docs.scala-lang.org/tutorials/FAQ/context-bounds

【讨论】:

    猜你喜欢
    • 2011-10-11
    • 1970-01-01
    • 2011-04-08
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 2011-07-05
    相关资源
    最近更新 更多