Skip to content

Commit 54d2410

Browse files
authored
Better way to get product elements (#264)
* Better way to get product elements Signed-off-by: Hongxin Liang <[email protected]> * More comment Signed-off-by: Hongxin Liang <[email protected]> --------- Signed-off-by: Hongxin Liang <[email protected]>
1 parent a4864aa commit 54d2410

File tree

3 files changed

+38
-7
lines changed

3 files changed

+38
-7
lines changed

flytekit-scala_2.13/src/main/scala/org/flyte/flytekitscala/SdkLiteralTypes.scala

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -229,11 +229,7 @@ object SdkLiteralTypes {
229229

230230
private def toStruct(product: Product): Struct = {
231231
def productToMap(product: Product): Map[String, Any] = {
232-
// by spec getDeclaredFields is not ordered but in practice it works fine
233-
// it's a lot better since Scala 2.13 because productElementNames was introduced
234-
// (product.productElementNames zip product.productIterator).toMap
235-
product.getClass.getDeclaredFields
236-
.map(_.getName)
232+
productElementNames(product)
237233
.zip(product.productIterator.toList)
238234
.toMap
239235
}

flytekit-scala_2.13/src/main/scala/org/flyte/flytekitscala/SdkScalaType.scala

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,7 @@ object SdkScalaType {
165165
): ju.Map[String, SdkBindingData[_]] = {
166166
value match {
167167
case product: Product =>
168-
value.getClass.getDeclaredFields
169-
.map(_.getName)
168+
productElementNames(product)
170169
.zip(product.productIterator.toSeq)
171170
.toMap
172171
.mapValues {
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
* Copyright 2023 Flyte Authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing,
11+
* software distributed under the License is distributed on an
12+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
13+
* KIND, either express or implied. See the License for the
14+
* specific language governing permissions and limitations
15+
* under the License.
16+
*/
17+
package org.flyte
18+
19+
package object flytekitscala {
20+
private[flytekitscala] def productElementNames(
21+
product: Product
22+
): List[String] = {
23+
try {
24+
// scala 2.13
25+
product.getClass
26+
.getMethod("productElementNames")
27+
.invoke(product)
28+
.asInstanceOf[Iterator[String]]
29+
.toList
30+
} catch {
31+
case _: Throwable =>
32+
// fall back to java's way, less reliable and with limitations
33+
product.getClass.getDeclaredFields.map(_.getName).toList
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)