Compliation failure - Generics with any data type

assert(yamlRoot is Map<,>, { “Invalid YAML document - the top level must be a map” })

what is wrong with this line , what can we have in Map Keys and values which can be any data type?

If you want to say you know nothing about the type of a generic you can use star projections.

Here’s a runnable (and editable! :writing_hand: ) example:

fun main() {
    val foo: Any = "Not a map"
    val isMap = foo is Map<*, *> // Here we say we use '*' to say we know *nothing* about the genaric types of this declaration.
    println("foo is map?: $isMap")
}

the problem is ,its not working with generics Map<,> ,getting incompatible type error

You’re posting Map<,> not Map<*, *>. Double check that in your code (you can try making your edits on the runnable examples too).

If you get a “Incompatible type error” it’s like the compiler doing your “is” check at compiler time and letting you know it doesn’t make sense.

For example, let’s try my previous runnable example but we’ll change foo’s type to String. This time the compiler knows the types won’t ever be the same–it knows an is check from String to Map<*, *> doesn’t make any sense as it will always fail. Try running it to see the error:

fun main() {
    val foo: String = "Not a map" // Notice this time we are not typing foo as 'Any' but keeping it as a 'String'
    val isMap = foo is Map<*, *>
    println("foo is map?: $isMap")
}

This is a good thing to get this error. You wouldn’t want to wait until your code ran just to be told a String will never be a Map.

Your yamlRoot, what type is it? It’s probably not a Map and better yet, the compiler knows that it isn’t. You can press ctrl+shift+p in IntelliJ to check your selection’s type.

1 Like

sorry for late reply , but it worked with adding type of Map attributes

1 Like