gpt4 book ai didi

多个隐式参数的Scala解析

转载 作者:行者123 更新时间:2023-12-01 05:23:09 26 4
gpt4 key购买 nike

在试图回答 this question ,我想出了以下代码:

    case class Monkey(bananas: Int) 
case class Tree(rings: Int)
case class Duck(quacks: Seq[String])

implicit class IntLike(val x : Int) extends AnyVal

implicit def monkey2Age(monkey: Monkey): IntLike = monkey.bananas / 1000
implicit def tree2Age(tree: Tree): IntLike = tree.rings
implicit def duck2Age(duck: Duck): IntLike = duck.quacks.size / 100000

def purchaseCandles[A <% IntLike]()(implicit age : A) = {
val asAge : IntLike = age
println(s"I'm going to buy $asAge candles!")
}

{
implicit val guest = Tree(50)
purchaseCandles()
}

请注意 IntLike只是为了让我相信这不是集中在 Int 上的问题.

这似乎是一个相当标准的隐式使用,如果不好的话,我期待它能够愉快地工作。然而,在调用 purchaseCandles() REPL 产生以下错误:

error: ambiguous implicit values: both value StringCanBuildFrom in object Predef of type => scala.collection.generic.CanBuildFrom[String,Char,String] and value guest of type Tree match expected type A



我一辈子都看不到这是怎么回事。 A 的 View 边界必然为 IntLike ,一种我刚刚发明的类型。 REPL 确认没有可用的隐式 View :

scala> implicitly[Tree => IntLike]

res14: Tree => IntLike = function1





scala> implicitly[scala.collection.generic.CanBuildFrom[String, Char, String] => IntLike]

:18: error: No implicit view available from scala.collection.generic.CanBuildFrom[String,Char,String] => IntLike.



那怎么能 StringCanBuildFrom是合适的类型?编译器是否能够解析多个依赖隐式,如果不能,为什么会显示这个错误?

最佳答案

在尝试回答之前,这里首先是简化的情况。请注意,您调用的是 purchaseCandles没有任何关于类型 A 的提示我认为这是问题的根源。

object Foo

def test[A <% Foo.type](implicit bar: A) {}

test

错误:
<console>:10: error: ambiguous implicit values:
both value StringCanBuildFrom in object Predef of type =>
scala.collection.generic.CanBuildFrom[String,Char,String]
and method conforms in object Predef of type [A]=> <:<[A,A]
match expected type A
test
^
StringCanBuildFrom似乎更像是一个令人困惑的错误消息。如果你专心 conforms在这里,这不起作用的原因可能会变得更清楚: Predef.conform声明每当您要求隐式转换 A => A ,这是通过身份来保证的。这样如果你有 def foo[B <% A](b: B) ,您可以随时调用 foo具有 A 类型的值无需定义任何类型的 A => A .

您要求解析未指定类型的隐式参数以及从该未指定类型到 IntLike 的转换。 .我认为这超出了隐式解析算法的范围。错误消息仍然有些奇怪。

关于多个隐式参数的Scala解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15433582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com