Hey! Is it possible to create a setup like this us...
# getting-started
j
Hey! Is it possible to create a setup like this using anonymous objects or something? (equivalent with using object literals en langs lite TypeScript)
Copy code
data class Farmer(
    val id: String,
    val farms: ???
)

f1 = Farmer("1", {
  "foo": <SomeClassInstance>,
  "bar": <SomeClassInstance>
})
f2 = Farmer("2", {
  "baz": <SomeClassInstance>,
  "qux": <SomeClassInstance>
})

// Access farms by name, checked at compile time
f1.farms.foo
f2.farms.qux
i.e. have the type of the property be inferred from the "keys" actually present in that specific instance.
a
Copy code
data class Farmer(
    val id: String,
    val farms: Map<String,<SomeClassInstance>>
)
No, because Kotlin is strongly statically typed
j
(aral?) I mean, technically it would still be statically type, it's just that the type definition itself would be inferred from the usage.
d
this is possible, to an extent
Copy code
data class Farmer<F>(
    val id: String,
    val farms: F
)

private val f1 = Farmer("1", object {
    val foo: String = "foo"
    val bar: String = "bar"
})

private val f2 = Farmer("2", object {
    val baz: Int = 4
    val qux: Int = 6
})

fun main() {
    println("${f1.farms.foo}, ${f1.farms.bar}, ${f2.farms.baz}, ${f2.farms.qux}")
}
j
To my understanding is that anonymous object's actual type is
Any
in a public context. But it works in local and private (not inline) declarations. So I thought, maybe it can be persuaded 😉 (it's for simplifying some test-cases)
@Damien O'Hara does the above work because it's effectivly local?
Ah, missed the type parameter 🙈
d
note that it will be quite hard to work with these since you won't be able to "name" the types anywhere. but the approach should work as long as you never have to state the type explicitly
j
I think that's fine. I just want to setup som fixture data that I can reference in test-cases. And I just want the IDE to help me suggest the named properties and have the compiler make sure I reference test-data that actually exists.
but the required
private
visibility modifier might make it impractical.
d
ah, you are right about that Any up-casting even with the type parameter. bit of a shame!
j
This might me ok:
Copy code
data class Farmer<TFarms, TTractors>(val id: String, val farms: TFarms, val tractors: TTractors)

object Farmer1Farms {
  const val FOO = "123"
  const val BAR = "123"
}

object Farmer1Tractors {
  const val SUPERPULLER = "WROOM"
  const val PLOWER = "YUMYUM"
}

val farmer1 = Farmer("farmer_1", Farmer1Farms, Farmer1Tractors)

fun main() = println("${farmer1.farms.BAR} uses ${farmer1.tractors.SUPERPULLER}")