Respond to an unknown method call: Difference between revisions

→‎{{header|Kotlin}}: Changed code so that the object itself now captures an attempt to call an unknown method.
(→‎{{header|Kotlin}}: Changed code so that the object itself now captures an attempt to call an unknown method.)
Line 591:
 
=={{header|Kotlin}}==
Kotlin JS does not currently target ECMAScript 2015 and so the Proxy object cannot be used for this task. The only way it can currently be accomplished is to use the Mozilla extension __noSuchMethod__ property which works with FireFox 43 but is no longer supported by more up to date versions:
{{incorrect|Kotlin|The object c is supposed to handle the situation, not the code site which tries to invoke foo on object c.}}
<lang scala>// Kotlin JS version 1.12.4-30 (FireFox 43)
 
class C // class with no methods {
// this method prevents a TypeError being thrown if an unknown method is called
fun __noSuchMethod__(id: String, args: Array<Any>) {
println("Class C does not have a method called foo$id")
if (args.size > 0) println("which takes arguments: ${args.asList()}")
}
}
 
fun main(args: Array<String>) {
val c: dynamic = C() // 'dynamic' turns off compile time checks
c.foo() // the compiler now allows this call even though foo() is undefined
try {
c.foo() // the compiler now allows this call even though foo() is undefined
}
catch (t: Throwable) {
if (t.message == "undefined is not a function") {
println("Class C does not have a method called foo")
}
else {
println(t.message)
}
}
}</lang>
 
9,479

edits