Göksenin Cakir
Göksenin Cakir

Reputation: 187

Equivalent of None in Scala

None is used to represent the absence of a value in Python.

For example, a node class for linked lists:

class Node:
    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next_node = next_node

Is there way to do this in Scala? I tried null but some sources advise against its usage.

class Node(new_data: Integer = null, new_next_node: Node = null) {
        var data = new_data
        var next_node = new_next_node

Upvotes: 2

Views: 940

Answers (2)

Hongxu Chen
Hongxu Chen

Reputation: 5350

In fact I also don't think use var is good practice in Scala. Perhaps you can define/initialize Node in the other way to avoid mutability.

But if you'd like to keep the code as much similar as the Python one, null is fine at least for new_next_node. And new_data can be initialized to some default value with type Int instead of using the boxed Integer; if new_data should be initialized by cases, it's better to use value: Option[Int] = None as @Sleiman Jneidi's answer has suggested.

Still, keep in mind that in Python, checking like if a is None is pythonic; however checking if a.isDefined against Option type is not quite scalaistic.

Upvotes: 3

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

The same in Scala but Scala is typed, so a value that might be absent has to have the type Option[T]

case class Node(value: Option[Int] = None, node: Option[Node] = None)

Upvotes: 10

Related Questions