<:< operator in scala

前端 未结 7 1057
说谎
说谎 2020-11-29 21:34

Can anybody provide some details on <:< operator in scala. I think:

if(apple <:< fruit)  //checks if apple is a subclass of fruit.         


        
7条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 22:09

    To better understand the implementation.

    sealed abstract class <:<[-From, +To] extends (From => To)
    implicit def conforms[A]: A <:< A = new (A <:< A) {def apply(x: A) = x}
    

    I tried to devise a simpler implementation. The following did not work.

    sealed class <:<[-From <: To, +To]
    implicit def conforms[A <: B, B]: A <:< B = new (A <:< B)
    

    At least because it won't type check in all valid use cases.

    case class L[+A]( elem: A )
    {
       def contains[B](x: B)(implicit ev: A <:< B) = elem == x
    }
    
    error: type arguments [A,B] do not conform to class <:<'s
           type parameter bounds [-From <: To,+To]
    def contains[B](x: B)(implicit ev: A <:< B) = elem == x
                                         ^
    

提交回复
热议问题