Custom property delegation for arrays using a map
Consider I'm trying to implement delegation by storing properties in a Map
instance, and one of the properties delegated is an array:
class Foo private constructor(map: Map<String, Any?>) {
constructor(value: Array<Byte>) : this(mapOf(Foo::value.name to value))
val value: Array<Byte> by map
}
object PropertyDelegationTest {
@JvmStatic
fun main(vararg args: String) {
val foo = Foo(arrayOf(42.toByte(), 127.toByte()))
println(foo.value[0]) // 42
println(foo.value[1]) // 127
}
}
The above compiles just fine and works as expected.
Now consider I want to enhance my property delegation mechanism by implementing a custom Map.getValue(thisRef: Any?, property: KProperty<*>)
extension method (overriding the default extension):
import kotlin.reflect.KProperty
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.starProjectedType
import kotlin.reflect.jvm.jvmName
// ...
operator fun <V, V1 : V> Map<in String, V>.getValue(thisRef: Any?, property: KProperty<*>): V1 {
val value = this[property.name]
?: throw NoSuchElementException("Key ${property.name} is missing in the map.")
val clazz = (value as Any)::class
@Suppress("UNCHECKED_CAST")
return when {
clazz.starProjectedType.isSubtypeOf(property.returnType) -> value as V1
else -> throw ClassCastException("${clazz.starProjectedType} (${clazz.jvmName}) cannot be cast to ${property.returnType}")
}
}
This fails at run time:
Exception in thread "main" java.lang.ClassCastException: kotlin.Array<*> ([Ljava.lang.Byte;) cannot be cast to kotlin.Array<kotlin.Byte>
at com.example.PropertyDelegationTestKt.getValue(PropertyDelegationTest.kt:30)
at com.example.Foo.getValue(PropertyDelegationTest.kt)
at com.example.PropertyDelegationTest.main(PropertyDelegationTest.kt:18)
Despite the effective JVM type is known ([Ljava.lang.Byte;
), Kotlin-specific run time type of the value is Array<*>
while Array<Byte>
is required. Consistently, clazz.typeParameters[0].upperBounds[0]
evaluates to kotlin.Any?
, not kotlin.Byte?
.
How do I implement my custom type checking which would also work correctly for arrays? Kotlin version is 1.2.71.
arrays kotlin
add a comment |
Consider I'm trying to implement delegation by storing properties in a Map
instance, and one of the properties delegated is an array:
class Foo private constructor(map: Map<String, Any?>) {
constructor(value: Array<Byte>) : this(mapOf(Foo::value.name to value))
val value: Array<Byte> by map
}
object PropertyDelegationTest {
@JvmStatic
fun main(vararg args: String) {
val foo = Foo(arrayOf(42.toByte(), 127.toByte()))
println(foo.value[0]) // 42
println(foo.value[1]) // 127
}
}
The above compiles just fine and works as expected.
Now consider I want to enhance my property delegation mechanism by implementing a custom Map.getValue(thisRef: Any?, property: KProperty<*>)
extension method (overriding the default extension):
import kotlin.reflect.KProperty
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.starProjectedType
import kotlin.reflect.jvm.jvmName
// ...
operator fun <V, V1 : V> Map<in String, V>.getValue(thisRef: Any?, property: KProperty<*>): V1 {
val value = this[property.name]
?: throw NoSuchElementException("Key ${property.name} is missing in the map.")
val clazz = (value as Any)::class
@Suppress("UNCHECKED_CAST")
return when {
clazz.starProjectedType.isSubtypeOf(property.returnType) -> value as V1
else -> throw ClassCastException("${clazz.starProjectedType} (${clazz.jvmName}) cannot be cast to ${property.returnType}")
}
}
This fails at run time:
Exception in thread "main" java.lang.ClassCastException: kotlin.Array<*> ([Ljava.lang.Byte;) cannot be cast to kotlin.Array<kotlin.Byte>
at com.example.PropertyDelegationTestKt.getValue(PropertyDelegationTest.kt:30)
at com.example.Foo.getValue(PropertyDelegationTest.kt)
at com.example.PropertyDelegationTest.main(PropertyDelegationTest.kt:18)
Despite the effective JVM type is known ([Ljava.lang.Byte;
), Kotlin-specific run time type of the value is Array<*>
while Array<Byte>
is required. Consistently, clazz.typeParameters[0].upperBounds[0]
evaluates to kotlin.Any?
, not kotlin.Byte?
.
How do I implement my custom type checking which would also work correctly for arrays? Kotlin version is 1.2.71.
arrays kotlin
1
Could you remove the explicit type check and instead do a safe cast toV1
and if that fails then throw the exception? e.g.return value as? V1 ?: throw ClassCastException(...
?
– Yoni Gibbs
Nov 20 at 11:20
@YoniGibbs This way it works, thanks a lot! Could you convert your comment to an answer so I can up-vote it?
– Bass
Nov 21 at 8:03
add a comment |
Consider I'm trying to implement delegation by storing properties in a Map
instance, and one of the properties delegated is an array:
class Foo private constructor(map: Map<String, Any?>) {
constructor(value: Array<Byte>) : this(mapOf(Foo::value.name to value))
val value: Array<Byte> by map
}
object PropertyDelegationTest {
@JvmStatic
fun main(vararg args: String) {
val foo = Foo(arrayOf(42.toByte(), 127.toByte()))
println(foo.value[0]) // 42
println(foo.value[1]) // 127
}
}
The above compiles just fine and works as expected.
Now consider I want to enhance my property delegation mechanism by implementing a custom Map.getValue(thisRef: Any?, property: KProperty<*>)
extension method (overriding the default extension):
import kotlin.reflect.KProperty
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.starProjectedType
import kotlin.reflect.jvm.jvmName
// ...
operator fun <V, V1 : V> Map<in String, V>.getValue(thisRef: Any?, property: KProperty<*>): V1 {
val value = this[property.name]
?: throw NoSuchElementException("Key ${property.name} is missing in the map.")
val clazz = (value as Any)::class
@Suppress("UNCHECKED_CAST")
return when {
clazz.starProjectedType.isSubtypeOf(property.returnType) -> value as V1
else -> throw ClassCastException("${clazz.starProjectedType} (${clazz.jvmName}) cannot be cast to ${property.returnType}")
}
}
This fails at run time:
Exception in thread "main" java.lang.ClassCastException: kotlin.Array<*> ([Ljava.lang.Byte;) cannot be cast to kotlin.Array<kotlin.Byte>
at com.example.PropertyDelegationTestKt.getValue(PropertyDelegationTest.kt:30)
at com.example.Foo.getValue(PropertyDelegationTest.kt)
at com.example.PropertyDelegationTest.main(PropertyDelegationTest.kt:18)
Despite the effective JVM type is known ([Ljava.lang.Byte;
), Kotlin-specific run time type of the value is Array<*>
while Array<Byte>
is required. Consistently, clazz.typeParameters[0].upperBounds[0]
evaluates to kotlin.Any?
, not kotlin.Byte?
.
How do I implement my custom type checking which would also work correctly for arrays? Kotlin version is 1.2.71.
arrays kotlin
Consider I'm trying to implement delegation by storing properties in a Map
instance, and one of the properties delegated is an array:
class Foo private constructor(map: Map<String, Any?>) {
constructor(value: Array<Byte>) : this(mapOf(Foo::value.name to value))
val value: Array<Byte> by map
}
object PropertyDelegationTest {
@JvmStatic
fun main(vararg args: String) {
val foo = Foo(arrayOf(42.toByte(), 127.toByte()))
println(foo.value[0]) // 42
println(foo.value[1]) // 127
}
}
The above compiles just fine and works as expected.
Now consider I want to enhance my property delegation mechanism by implementing a custom Map.getValue(thisRef: Any?, property: KProperty<*>)
extension method (overriding the default extension):
import kotlin.reflect.KProperty
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.starProjectedType
import kotlin.reflect.jvm.jvmName
// ...
operator fun <V, V1 : V> Map<in String, V>.getValue(thisRef: Any?, property: KProperty<*>): V1 {
val value = this[property.name]
?: throw NoSuchElementException("Key ${property.name} is missing in the map.")
val clazz = (value as Any)::class
@Suppress("UNCHECKED_CAST")
return when {
clazz.starProjectedType.isSubtypeOf(property.returnType) -> value as V1
else -> throw ClassCastException("${clazz.starProjectedType} (${clazz.jvmName}) cannot be cast to ${property.returnType}")
}
}
This fails at run time:
Exception in thread "main" java.lang.ClassCastException: kotlin.Array<*> ([Ljava.lang.Byte;) cannot be cast to kotlin.Array<kotlin.Byte>
at com.example.PropertyDelegationTestKt.getValue(PropertyDelegationTest.kt:30)
at com.example.Foo.getValue(PropertyDelegationTest.kt)
at com.example.PropertyDelegationTest.main(PropertyDelegationTest.kt:18)
Despite the effective JVM type is known ([Ljava.lang.Byte;
), Kotlin-specific run time type of the value is Array<*>
while Array<Byte>
is required. Consistently, clazz.typeParameters[0].upperBounds[0]
evaluates to kotlin.Any?
, not kotlin.Byte?
.
How do I implement my custom type checking which would also work correctly for arrays? Kotlin version is 1.2.71.
arrays kotlin
arrays kotlin
asked Nov 20 at 9:50
Bass
1,67721646
1,67721646
1
Could you remove the explicit type check and instead do a safe cast toV1
and if that fails then throw the exception? e.g.return value as? V1 ?: throw ClassCastException(...
?
– Yoni Gibbs
Nov 20 at 11:20
@YoniGibbs This way it works, thanks a lot! Could you convert your comment to an answer so I can up-vote it?
– Bass
Nov 21 at 8:03
add a comment |
1
Could you remove the explicit type check and instead do a safe cast toV1
and if that fails then throw the exception? e.g.return value as? V1 ?: throw ClassCastException(...
?
– Yoni Gibbs
Nov 20 at 11:20
@YoniGibbs This way it works, thanks a lot! Could you convert your comment to an answer so I can up-vote it?
– Bass
Nov 21 at 8:03
1
1
Could you remove the explicit type check and instead do a safe cast to
V1
and if that fails then throw the exception? e.g. return value as? V1 ?: throw ClassCastException(...
?– Yoni Gibbs
Nov 20 at 11:20
Could you remove the explicit type check and instead do a safe cast to
V1
and if that fails then throw the exception? e.g. return value as? V1 ?: throw ClassCastException(...
?– Yoni Gibbs
Nov 20 at 11:20
@YoniGibbs This way it works, thanks a lot! Could you convert your comment to an answer so I can up-vote it?
– Bass
Nov 21 at 8:03
@YoniGibbs This way it works, thanks a lot! Could you convert your comment to an answer so I can up-vote it?
– Bass
Nov 21 at 8:03
add a comment |
1 Answer
1
active
oldest
votes
You could remove the explicit type check and instead do a safe cast to V1
and if that fails then throw the exception, e.g.
return value as? V1 ?: throw ClassCastException(...
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53390285%2fcustom-property-delegation-for-arrays-using-a-map%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You could remove the explicit type check and instead do a safe cast to V1
and if that fails then throw the exception, e.g.
return value as? V1 ?: throw ClassCastException(...
add a comment |
You could remove the explicit type check and instead do a safe cast to V1
and if that fails then throw the exception, e.g.
return value as? V1 ?: throw ClassCastException(...
add a comment |
You could remove the explicit type check and instead do a safe cast to V1
and if that fails then throw the exception, e.g.
return value as? V1 ?: throw ClassCastException(...
You could remove the explicit type check and instead do a safe cast to V1
and if that fails then throw the exception, e.g.
return value as? V1 ?: throw ClassCastException(...
answered Nov 21 at 8:06
Yoni Gibbs
953113
953113
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53390285%2fcustom-property-delegation-for-arrays-using-a-map%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Could you remove the explicit type check and instead do a safe cast to
V1
and if that fails then throw the exception? e.g.return value as? V1 ?: throw ClassCastException(...
?– Yoni Gibbs
Nov 20 at 11:20
@YoniGibbs This way it works, thanks a lot! Could you convert your comment to an answer so I can up-vote it?
– Bass
Nov 21 at 8:03