I have an object FakeDefault
which I later dishonestly cast to a lambda type to get the compiler to let me use it as a default argument for a context lambda parameter. I simply need to check if that default argument was used or not. In essence like so
object FakeDefault
def f(g: (x: Int) ?=> Int = FakeDefault.asInstanceOf[(x: Int) ?=> Int]) = {
if g == FakeDefault then
println("No argument provided")
else
println("Argument was provided")
}
f() // should see "No argument provided"
f(x + 1) // should see "Argument was provided"
Of course this code won’t work as we must cast g
back to his true type of FakeDefault
. I attempt this
object FakeDefault
def asFakeDefault[T](f: T) =
f.asInstanceOf[FakeDefault.type]
def f(g: (x: Int) ?=> Int = FakeDefault.asInstanceOf[(x: Int) ?=> Int]) = {
if asFakeDefault[(x: Int) ?=> Int](g) == FakeDefault then
println("No argument provided")
else
println("Argument was provided")
}
This clears all problems on the type-system, it’s allowed to run. But we get a runtime error on invocation
f(x + 1)
Caused by: java.lang.ClassCastException: class Playground$$$Lambda$17889/0x00007fd17a6ccab8
cannot be cast to class Playground$FakeDefault$(Playground$$$Lambda$17889/0x00007fd17a6ccab8
and Playground$FakeDefault$ are in unnamed module of loader sbt.internal.BottomClassLoader @676f8d8e)
I also have ideas about putting a marker value on the original object and checking if it has that marker.
trait HasMarker:
def marker: String
object FakeDefault extends HasMarker:
val marker = "marker"
def asHasMarker[T](f: T) =
f.asInstanceOf[HasMarker]
def f(g: (x: Int) ?=> Int = FakeDefault.asInstanceOf[(x: Int) ?=> Int]) = {
if asHasMarker[(x: Int) ?=> Int](g).marker == "marker" then
println("No argument provided")
else
println("Argument was provided")
}
But face similar error.
Does scala provide any dynamic typing or runtime reflection facilities, at all, to pass in FakeDefault
as the default value for the lambda parameter, and then immediately check if that was in fact what was passed? I am also using Scalajs, if that makes a difference. Any tricks are acceptable.
(Please don’t comment “why are you doing this”, “you shouldn’t do this”, “this isn’t how static languages work”, “use Option
”, etc. I already know. Please only comment if you have a way to make this work, or statement of confidence that this is 100% not possible by any technique. Thank you)