【问题标题】:How does <:< work?<:< 如何工作?
【发布时间】:2011-07-21 14:49:14
【问题描述】:
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>

&lt;:&lt; 约束如何工作?或者更准确地说,提供&lt;:&lt; 实例的隐式定义在哪里?

【问题讨论】:

标签: scala


【解决方案1】:

您可以在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] 

【讨论】:

    【解决方案2】:

    它在 Predef 对象中。

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

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 2016-11-16
      • 2011-07-20
      • 2013-06-23
      • 2011-02-10
      相关资源
      最近更新 更多