Do not allow to delegate readonly property to a map with incompatible value type.
Infer type of delegated readonly property from the map value type.
This commit is contained in:
@@ -11,7 +11,7 @@ package kotlin.properties
|
||||
*
|
||||
* @throws NoSuchElementException when the map doesn't contain value for the property name and doesn't provide an implicit default (see [withDefault]).
|
||||
*/
|
||||
public fun <V> Map<in String, *>.getValue(thisRef: Any?, property: PropertyMetadata): V = getOrImplicitDefault(property.name) as V
|
||||
public fun <V, V1: V> Map<in String, @Exact V>.getValue(thisRef: Any?, property: PropertyMetadata): V1 = getOrImplicitDefault(property.name) as V1
|
||||
|
||||
/**
|
||||
* Returns the value of the property for the given object from this mutable map.
|
||||
|
||||
@@ -9,11 +9,13 @@ class ValByMapExtensionsTest {
|
||||
val map: Map<String, String> = hashMapOf("a" to "all", "b" to "bar", "c" to "code")
|
||||
val genericMap = mapOf<String, Any?>("i" to 1, "x" to 1.0)
|
||||
|
||||
val a: String by map
|
||||
val a by map
|
||||
val b: String by map
|
||||
val c: Any by map
|
||||
val d: String? by map
|
||||
val e: String? by map.withDefault { "default" }
|
||||
val e: String by map.withDefault { "default" }
|
||||
val f: String? by map.withDefault { null }
|
||||
// val n: Int by map // prohibited by type system
|
||||
val i: Int by genericMap
|
||||
val x: Double by genericMap
|
||||
|
||||
@@ -23,6 +25,7 @@ class ValByMapExtensionsTest {
|
||||
assertEquals("bar", b)
|
||||
assertEquals("code", c)
|
||||
assertEquals("default", e)
|
||||
assertEquals(null, f)
|
||||
assertEquals(1, i)
|
||||
assertEquals(1.0, x)
|
||||
assertTrue(assertFails { d } is NoSuchElementException)
|
||||
|
||||
Reference in New Issue
Block a user