Black monkey house: Scala object can not be generic

We can not add to the object type parameter. For example, a variable list. A list of elements of type T is either empty, either a T type head, tail type List [T] of the node

abstract class List[+T]{
    def isEmpty:Boolean
    def head:T
    def tail:List[T]
}

class Node[T](val head:T,val tail:List[T]) extends List[T]{
    def isEmpty = false
}

class Empty[T] extends List[T]{
    def isEmpty = true
    def head = throw new UnsupportedOperationException
    def tail = throw new UnsupportedOperationException
}

尖叫提示:这里我用Node和Empty是为了让讨论对Java程序员而言比较容易。如果你对Scala列表很熟悉的话,之哟啊在脑海中将其替换成::和Nil即可

Empty defined as the class looks a little silly, because it does not state. However, you can not simply turn it into an object:
Object Empty [T] the extends List [T] // error

You can not add a parameterized type to object. In this case, the amount of the solution is that we inherited List [Nothing]:
Object Empty the extends List [Nothing]

You should also remember, Nothing type is a subtype of all types. Thus, when we list configured as a single element,
Val = new new List1 the Node (42 is, Empty)

Type checking is successful. The covariant rules, List [Nothing] can be converted into to a List [Int], and thus Node [Int] constructor can be called

Reproduced in: https: //www.jianshu.com/p/49566fee14bb

Guess you like

Origin blog.csdn.net/weixin_33904756/article/details/91182531