Sticky wildcard border

I came across this post on the scala forum.

Here is a brief description:

I just realized that the scala compiler does not seem to "transfer" type boundaries to wildcards:

scala> class Foo { def foo = 42 }
defined class Foo
scala> class Bar[A <: Foo](val a: A)
defined class Bar
scala> def bar(x: Bar[_]) = x.a.foo
:7: error: value foo is not a member of Any

I would expect the bar parameter of the method still top bound by Foo, although its exact type parameter does not matter in the method. Is there a specific reason for this behavior?

Then the debate about the interpretation of Spec is discussed :)

Explanation?

In the end, the poster offers the following explanation:

, Bar [_], Bar [A]. , , . def bar [A] (x: Bar [A], y: Bob [A]) , . , .

,

def bar[A](x: Bar[A])

, Bar .

, , :

def bar(x: Bar[_], y : Bob[_])

:

def bar(x: Bar[_ <: Foo]) = x.a.foo

, , :

abstract class Tree[T <: Tree[T]] { val subTree : List[T] }

, ( Tree ), :

def size( tree : Tree[_] ) = tree.subTree.size + tree.subTree.map(size(_)).sum

, , subTree List [Any], :

def size[T <: Tree[T]]( tree : T ) = ...

:

class OwnATree( val myTree : Tree[_] ){}

class OwnATree[T <: Tree[T]]( val myTree : T ){}

.. ..

, - -:)

+5
1

, size OwnATree, - :

def size(tree: Tree[T] forSome { type T <: Tree[T] }): Int =
  tree.subTree.size + tree.subTree.map(size(_)).sum

class OwnATree(val myTree: Tree[T] forSome { type T <: Tree[T] })

Tree[_] - - . ,

def size(tree: Tree[_]): Int = ...

:

def size(tree: Tree[T] forSome { type T }): Int = ...

, , .

+5

All Articles