Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Node[TypeOne <: Node[TypeOne]] in scala mean?

Tags:

generics

scala

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?

like image 912
Salil Surendran Avatar asked Sep 06 '16 08:09

Salil Surendran


2 Answers

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.

like image 193
Jean-Philippe Pellet Avatar answered Oct 31 '22 16:10

Jean-Philippe Pellet


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:

  • twitter scala school: https://twitter.github.io/scala_school/advanced-types.html
  • wikipedia: https://en.wikipedia.org/wiki/Bounded_quantification
  • blog post http://blog.originate.com/blog/2014/02/27/types-inside-types-in-scala/
like image 44
handler Avatar answered Oct 31 '22 14:10

handler