Reputation: 2335
I am unable to figure out how this code works?
class Node[TypeOne <: Node[TypeOne]] {
var x: TypeOne = _
}
object Tree extends App {
val treeNode = new Node[String]
treeNode.x = "ten"
//treeNode.x = new TreeNode[String]
}
Initially I thought by the signature class Node[TypeOne <: Node[TypeOne]] it meant that any variable like x of type TypeOne had to be a of type Node or it's subclass but it seems that is not true since I can create a val treeNode of type Node[String] and Node[Int]. So what does this signature do?
Upvotes: 5
Views: 62
Reputation: 1483
this is referred to as "f bounded polymorphism" in scala. there's a lot of info out there about it, so instead of trying to enumerate all of that here, i'll just share some helpful links:
Upvotes: 3
Reputation: 60016
This pattern is usually used for base classes or traits who want to know their concrete subtype statically. Most probably, the library designer expects you to extends Node
:
class MyNode extends Node[MyNode]
and then use MyNode
instead of Node
directly.
Upvotes: 3