user404345
user404345

Reputation:

Parameterized Option Type

I understand that Options are parameterised i.e. Option[T] but how do I specify a nested parameterised type e.g. Option[Node[T]]?

I have this class definition

class Node[T <: Serializable] private(val path: String, val data: T, val parent: Option[Node[T]] = None) {
...
}

and when i construct it as new Node[String]("/", "Test", None) scalac chokes as it expects Node[String], not Node.type. I then tried

new Node[String](path = "/", data = "Test", parent = None[Node[String]])

But None does not accept parameters

Any ideas?

Upvotes: 2

Views: 119

Answers (2)

smarquis
smarquis

Reputation: 540

So None is always None, without parameter, as somebody explains.

Another pitfall is that String is not a subtype of Serializable, but of java.io.Serializable:

This works fine:

scala> class Node[T <: java.io.Serializable ] (val path: String, val data: T, val parent: Option[Node[T]] = None) { }
defined class Node

scala> new Node("/", "")
res19: Node[String] = Node@4b520ea8

Upvotes: 3

alextsc
alextsc

Reputation: 1368

Your code is just fine: you just have to wrap a present value in Some(). Option can be represented as Some or None for present and not-present. If you want the value to be absent you can call it with:

parent = None

None does not take parameters (since it represents an absent value) and it's also an object, i.e. only one instance exists. But it has a type parameter Nothing, which is a subtype of any other type, so it works just fine in place where an Option[Node[T]] is expected.

If you want a value present you have to wrap it in Some, like this:

parent = Some(new Node[String]("/", "Test", None))

Upvotes: 0

Related Questions