[英]Unexpected implicit resolution in scala
I was trying to work out some simple examples of type-level programming in Scala 2.11. 我试图在Scala 2.11中得出一些简单的类型级编程示例。 Here is a function to tell type equality: 这是一个告诉类型相等的函数:
def type_==[A, B](implicit ev: A =:= B = null) = ev != null
Here =:=
is defined in the prelude, but for our purpose, even a simple definition such as =:=
是在序言中定义的,但出于我们的目的,即使是简单的定义,例如
class =:=[A, B]
implicit def equalTypeInstance[A] = new =:=[A, A]
would do. 会做。 To be sure, can do 可以确定
type_==[Int, String] // false
type_==[Int, Int] // true
Next, I encode booleans as types - to make things simple, I avoid to define any operation 接下来,我将布尔值编码为类型-为了使事情变得简单,我避免定义任何操作
sealed trait Bool
trait True extends Bool
trait False extends Bool
I can again check that 我可以再次检查
type_==[True, True] // true
So I thought I might convert Bool
to Boolean
by doing 所以我想我可以通过将Bool
转换为Boolean
def bool2boolean[A <: Bool] = type_==[A, True]
Here's the catch: 这是要抓住的地方:
bool2boolean[True] // false
Can anyone explain the reason why? 谁能解释原因?
Implicits don't magically pass through functions - each function creates its own scope, and the implicit resolution happens there: 隐式方法不会神奇地传递函数-每个函数都创建自己的作用域,并且隐式解决方案在那里发生:
def bool2boolean[A <: Bool] = type_==[A, True]
In this scope the compiler attempts to resolve a =:=[A, True]
, can't find one, and so this function always returns False
. 在这种情况下 ,编译器尝试解析=:=[A, True]
,找不到一个,因此此函数始终返回False
。
Try passing the evidence through this function: 尝试通过此函数传递证据:
def bool2boolean[A <: Bool](implicit ev: A =:= True = null) =
type_==[A, True]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.