``` inline fun <reified T> Config.xAxis(bloc...
# announcements
b
Copy code
inline fun <reified T> Config.xAxis(block: T.() -> Unit, axisType: AxisType) {
   xAxis = when (T::class.java) {
       NumericAxis::class.java -> {
         NumericAxis().apply(block)
       }
       else -> throw UnsupportedOperationException("currently unsupported")
   }
}
Why does it not compile? Any thoughts?
m
What's the compile error?
What is the type of
xAxis
?
a
it compiles if I do:
Copy code
xAxis = when (T::class) {
        NumericAxis::class -> NumericAxis().also { block(it as T) }
        else -> throw UnsupportedOperationException("currently unsupported")
    }
👍 3
b
@marstran
xAxis
is a DSL function. Usage is like,
Copy code
xAxis<NumericAxis> {
}
@arekolek So
block
does not take any parameter. It has receiver type
T
which comes from DSL usage. We did,
Copy code
fun <T> Config.xAxis(block: T.() -> Unit, axisType: AxisType) {
    xAxis = when (axisType) {
        AxisType.NUMERIC -> NumericAxis().apply(block as NumericAxis.() -> Unit)
        else -> throw UnsupportedOperationException("currently unsupported")
    }
}
But looking to avoid casting.
m
@BMG But your doing
xAxis = when(axisType) { .... }
. You can't assign anything to a function.
a
it could be a property of
Config
that’s what I assumed
b
@marstran Ah sorry, I did not clarify.
xAxis
inside that function is a property of type
Axis
.
@arekolek Just got it to work with your code. Thanks!
👍 1
a
@BMG and regarding
block
having a receiver instead of parameter, see my related question here https://kotlinlang.slack.com/archives/C0B8MA7FA/p1504173358000320?thread_ts=1504173358.000320
K 1
b
@arekolek Nice! I was pleasantly surprised when it worked. TIL for me 🙂
s
There is a similar parameter usage in Android KTX as well
Copy code
inline fun <reified T : ViewGroup.LayoutParams> View.updateLayoutParams(block: T.() -> Unit) {
    val params = layoutParams as T
    block(params)
    layoutParams = params
}