scala> implicitly[Int <:< AnyVal]
res0: <:<[Int,AnyVal] = <function1>
scala> class Foo
defined class Foo
scala> class Bar extends Foo
defined class Bar
scala> implicitly[Foo <:< Bar]
<console>:8: error: could not find implicit value for parameter e: <:<[Foo,Bar]
implicitly[Foo <:< Bar]
^
scala> implicitly[Bar <:< Foo]
res2: <:<[Bar,Foo] = <function1>
<:<
约束如何工作?或者更准确地说,提供<:<
的实例的隐式定义在哪里?
答案 0 :(得分:8)
您可以在Predef中找到它。隐式方法conforms[A]
提供了这些证据:
implicit def conforms[A]: A <:< A = new (A <:< A) { def apply(x: A) = x }
你可以自己尝试自己实现它,以便更清楚:
abstract class subclassOf[-From, +To] extends (From => To)
implicit def subclassOfCheck[A]: A subclassOf A = new (A subclassOf A) { def apply(x: A) = x }
implicitly[Int subclassOf AnyVal]
class Foo
class Bar extends Foo
implicitly[Bar subclassOf Foo]
答案 1 :(得分:0)
它位于Predef对象中。
scala> implicitly[Int <:< AnyVal]
res1: <:<[Int,AnyVal] = <function1>
scala> :type res1
Predef$<:<[Int,AnyVal]