angryziber / kotlin-puzzlers

A collection of Kotlin Puzzlers
419 stars 58 forks source link

'N Sync puzzler #74

Open TWiStErRob opened 4 years ago

TWiStErRob commented 4 years ago

Late night brain-fart, could be fun. Inspiration: https://youtu.be/MYQWtNG2so8?t=1101 (took the section heading too literally)

package by

object by {
    val by: by by by
}

operator fun `by`.getValue(by: by, prop: Any): by =
    TODO("by by by")

fun main() {
    println(by.by.by)
}

Not sure what the question would be, I guess "What happens when you try to compile & run this?"

Result (click to expand) ``` /** Exception in thread "main" java.lang.ExceptionInInitializerError at b.y.ByKt.main(by.kt:11) at b.y.ByKt.main(by.kt) Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method b.y.ByKt.getValue, parameter $this$getValue at b.y.ByKt.getValue(by.kt) at b.y.by.getBy(by.kt) at b.y.by.(by.kt:4) ... 2 more */ ``` Explanation: the last `by` in `val by: by by by` refers to the same property it's trying to initialize. (Suprising: the backticks are required to compile, not sure yet why.)
Generic version, for laughs This was an intermediate version, then I realized that `getValue` is enough to make it work. ```kotlin package b.y open class by> { val by: by by by } operator fun `by`<*>.getValue(by: by<*>, prop: Any): Nothing = TODO("by by by") fun main() { class by : b.y.by() println(b.y.by().by) } ```