2011-07-21 184 views
5
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> 

如何<:<約束的工作?或者更準確地說,那裏是提供的<:<的情況下,隱含的定義是什麼?<:<工作?

+3

的可能重複[什麼做<<,<%<,和=:= Scala中2.8的意思是,和他們在記錄其中](http://stackoverflow.com/questions/3427345/what-do-and-mean-in-scala-2-8-and-where-are? - 它們詳細記錄) – oluies

+0

http://stackoverflow.com/questions/2603003/operator-in-scala – oluies

回答

0

它在PREDEF對象。

scala> implicitly[Int <:< AnyVal] 
res1: <:<[Int,AnyVal] = <function1> 

scala> :type res1 
Predef$<:<[Int,AnyVal] 
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]