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?
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With