Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 530 Vote(s) - 3.46 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Implement Hashmap with different value types in Kotlin

#1
Is it possible to have a hashmap in Kotlin that takes different value types?

I've tried this:

val template = "Hello {{world}} - {{count}} - {{tf}}"

val context = HashMap<String, Object>()
context.put("world", "John")
context.put("count", 1)
context.put("tf", true)

... but that gives me a type mismatch (apparantly `"John"`, `1` and `true` are not Objects)

In Java you can get around this by creating types `new String("John")`, `new Integer(1)`, `Boolean.TRUE`, I've tried the equivalent in Kotlin, but still getting the type mismatch error.

context.put("tf", Boolean(true))

Any ideas?
Reply

#2
In Kotlin, [`Any`][1] is the supertype of all the other types, and you should replace Java `Object` with it:

val context = HashMap<String, Any>()
context.put("world", "John")
context.put("count", 1)
context.put("tf", true)


[1]:

[To see links please register here]

Reply

#3
For new visitors,It can also be done with this

val a= hashMapOf<Any,Any>( 1 to Exception(), 2 to Throwable(), Object() to 33)

Where both keys and values can be of any type.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through