subho subho - 3 months ago 13
Scala Question

Unified Type System - Any, AnyRef, AnyVal in scala

I am trying to learn scala types.
I am learning from below website.

http://ktoso.github.io/scala-types-of-types/

Under the topic.
Unified Type System -

Any
,
AnyRef
,
AnyVal


class Person

val allThings = ArrayBuffer[Any]()

val myInt = 42 // Int, kept as low-level `int` during runtime

allThings += myInt // Int (extends AnyVal)
// has to be boxed (!) -> becomes java.lang.Integer in the collection (!)

allThings += new Person() // Person (extends AnyRef), no magic here


When i tried the above code in scala worksheet.
I am getting error in the 2nd line.

val allThings = ArrayBuffer[Any]() as value error: value ArrayBuffer


Please find my code in scala worksheet.

object test1 {
println("Welcome to the Scala worksheet")

class Person

val allThings = ArrayBuffer[Any]()

val myInt = 42 // Int, kept as low-level `int` during runtime

allThings += myInt // Int (extends AnyVal)
// has to be boxed (!) -> becomes java.lang.Integer in the collection (!)

allThings += new Person() // Person (extends AnyRef), no magic here

}


Please help me.

Thanks and Regards,

Answer

TL;DR: You need to either import ArrayBuffer of use the FQCN.

FQCN

ArrayBuffer is not one of your classes, it is a class in the Scala library, it lives at scala.collection.mutable.ArrayBuffer. scala.collection.mutable is not one of the packages imported by default:

  • java.lang._
  • scala._
  • scala.Predef._

So in order to use it you need to use the Fully Qualified Class Name:

val allThings = scala.collection.mutable.ArrayBuffer[Any]()

Importing

You can tell Scala that you wish to refer to scala.collection.mutable.ArrayBuffer as simply ArrayBuffer, this is called an import.

You need to add the following code before your code:

import scala.collection.mutable.ArrayBuffer

Then whenever you use ArrayBuffer, the compiler will use scala.collection.mutable.ArrayBuffer.

Comments