Tom
Tom

Reputation: 6332

When can we NOT specify type parameter

Given the following test case, there are 3 scenarios in it. I would ask what's the rules here that govern when we must and when we don't have to specify the type parameter

  @Test
  def testTypeParamter(): Unit = {

    class Cat[A]

    //1. Don't need to specify the type parameter for Cat
    def getCat() = new Cat
    println(getCat())

    import scala.collection.mutable.ArrayBuffer

    //2. Don't need to specify the type parameter for ArrayBuffer

    val bf = new ArrayBuffer()
    println(bf)

    //3. Do need to specify the type parameter for ArrayBuffer to make bf2 += 1 work
    val bf2 = new ArrayBuffer[Int]()
    bf2 += 1

    println(getCat())
  }

Compared with #2 and #3, what can we do if we create an empty ArrayBuffer without type parameter

Upvotes: 0

Views: 191

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

You don't need to specify the type parameter when Scala infers the type you want. This inference is based both on arguments to method/constructor (none in your case) and on expected type (none in your case). You could also have e.g.

val buffer: ArrayBuffer[Long] = new ArrayBuffer()

Upvotes: 0

prayagupadhyay
prayagupadhyay

Reputation: 31192

Let's check in REPL,

1.1 scenario without a type param

scala> class Bag[A]
defined class Bag

scala> def createBag = new Bag
createBag: Bag[Nothing]

1.2 ArrayBuffer[T] without type param

scala>  val buffer = new ArrayBuffer()
buffer: scala.collection.mutable.ArrayBuffer[Nothing] = ArrayBuffer()

In both case you see the default type parameter as scala.Nothing. scala.Nothing is abstract and can not be instantiated which means you can't operate on your generics instance like buffer+=new String("apple") etc because Nothing is at the bottom of scala class hierarchy.

2. providing type parameter

This is obviously the purpose of having generic type that you want Generics for certain type.

scala> var buffer = new ArrayBuffer[Long]()
buffer: scala.collection.mutable.ArrayBuffer[Long] = ArrayBuffer()

scala> buffer+=89l
res0: scala.collection.mutable.ArrayBuffer[Long] = ArrayBuffer(89)

Upvotes: 3

Related Questions