Search code examples
scalalistvariablesfillmutable

How to initialize MutableList with default values using a variable?


Class List contains such method called "fill", but I couldn't find any similar method in MutableList class.

var fields: MutableList[MutableList[Boolean]] = new MutableList.fill(size, size)(true)

^ doesn't work


Solution

  • fill is a method on the companion object of MutableList (similar to how it's defined on Lists companion). This works:

    val fields: MutableList[MutableList[Boolean]] = MutableList.fill(size, size)(true)
    

    scala> val fields: MutableList[MutableList[Boolean]] = MutableList.fill(2, 2)(true)
    fields: scala.collection.mutable.MutableList[scala.collection.mutable.MutableList[Boolean]] = MutableList(MutableList(true, true), MutableList(true, true))