1

Nowadays I am learning Kotlin and I have a question. I'm writing the code below and I get the error "The integer literal does not conform to the expected type String".

fun main() {

fun <Any> MutableList<Any>.yaz(name : Any) : Any = name;

var mutableList : MutableList<String> = ArrayList<String>()

println(mutableList.yaz(1))
println(mutableList.yaz("Selam"))

}

Where am I making a mistake? I would be very happy if you can help. Thanks!

It works when I write as follows, but I didn't understand why.

fun <Any> MutableList<out Any>.yaz(name : Any) : Any = name;
Hasan Cihad Altay
  • 171
  • 1
  • 4
  • 11
  • Are you intending `Any` to mean the usual type `kotlin.Any`? Because it's not: by specifying `` it's simply the name of the type parameter within the definition of `yaz()`. (That's why we usually use single letters for type parameters, to avoid this sort of confusion.) – gidds Mar 12 '21 at 00:45
  • What's the difference between and ? @gidds – Hasan Cihad Altay Mar 12 '21 at 01:17

1 Answers1

0

As @gidds said in the comments, you might be writing Any to mean the Any type in Kotlin, however as you have specified Any as a generic of the function yaz, then it no longer represents a reified type.

Explicitly,

fun <Any> MutableList<Any>.yaz(name : Any) : Any = name;

is equivalent to

fun <T> MutableList<T>.yaz(name : T) : T = name;

So therefore the reason that your example doesn't compile is because you are specifying that the type of MutableList should be the same as the type of the name parameter, which is not true when using a MutableList<String> and name = 1.


The out parameter in Koltin declares something as a producer, but there is a very detailed explanation here that will explain it better than I can. However the fact that your example with out works fine is a mystery to me, so it would be nice to have someone clear that up.

Henry Twist
  • 5,666
  • 3
  • 19
  • 44