MH MH
MH MH

Reputation: 41

Can't change the mutableListOf( ) values


Kindly look at the code,

fun main()
{
var y = mutableListOf( "MH", 19, true  )

        y[0] = "value4"     // showing error in this line

        println( y[0] )
}

When i try to change the "MH" value. it shows me the following error.

Kotlin: Type mismatch: inferred type is String but Nothing was expected


Thanks in advance.

Upvotes: 2

Views: 175

Answers (2)

Eric Gacoki
Eric Gacoki

Reputation: 121

you could also try to specify the type explicitly

val y: MutableList<Any> = mutableListOf( "MH", 19, true )

#b😃nus

even though y is a val, its value is mutable since it has been assigned to a mutableList but still can't be reassigned. The same scenario applies to other mutable collections.

for more information see https://kotlinlang.org/docs/reference/collections-overview.html

Upvotes: 0

Tenfour04
Tenfour04

Reputation: 93872

You have mixed types. All of them are subclasses of Any, but also subtypes of Comparable<*>. The compiler picks the lower type when you leave it to be implicitly chosen. In this case, the lower type is Comparable<*>, but the star projection prevents you from adding anything to the list.

To prevent the implicit typing, specify it explicitly:

var y = mutableListOf<Any>( "MH", 19, true  )

Upvotes: 2

Related Questions