1

I have just started to explore Scala. suppose I have the following code:

abstract class Shape
case class Square() extends Shape
case class Circle() extends Shape
case class Triangle() extends Shape

Having that, I can define a reference referring to Shape in java, and then I can store objects of Shape subclasses in it as bellow:

Shape s=null;
s=new Circle(); 
s=new Square();
s=new Triangle();

my Question: what is the above code counterpart in scala (note that I do want to define only one variable, namely s here)

2 Answers 2

1

You can write a code like this:

var s: Shape = null
s = new Circle()
s = new Square()
s = new Triangle()

However, Scala is originally meant to be used functionally. So you should use val instead of var as much as possible. val is very similar to final in Java.

Every time you use var instead of val you should be 100% sure you want to do that.

Moreover, try to avoid nulls at all. Instead, use Option. Maybe you're interested in some literature such as this book

Sign up to request clarification or add additional context in comments.

Comments

0

Simple:

var s: Shape = null
s = Circle()
s = Square()
s = Triangle()

If you're an Option-zealot:

var s: Option[Shape] = None
s = Some(Circle())
s = Some(Square())
s = Some(Triangle())

If you're a val-zealot:

val s1 = Circle()
val s2 = Square()
val s3 = Triangle()

Contrary to popular belief, var and null are totally fine in small scopes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.