unknown9070
unknown9070

Reputation: 51

How does <:< work?

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>

How does <:< constraint work? Or more precisely, where is the implicit definition that supplies the instances of <:<?

Upvotes: 5

Views: 641

Answers (2)

tenshi
tenshi

Reputation: 26566

You can find it in Predef. Implicit method conforms[A] provides these evidences:

implicit def conforms[A]: A <:< A = new (A <:< A) { def apply(x: A) = x }

You can actually try to implement it yourself in order to make it more clear:

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] 

Upvotes: 8

Kim Stebel
Kim Stebel

Reputation: 42047

It's in the Predef object.

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

scala> :type res1
Predef$<:<[Int,AnyVal]

Upvotes: 0

Related Questions