Skip to content

Surprise in double dispatch of operators #544

@teunbrand

Description

@teunbrand

Apologies for the frequent issue posting.
When writing an S7 method for an operator and S3 class, we seem to bypass the method when the RHS is not also an S7 class.
In the example below, I expected foo + 10 to also return "success".

library(S7)

foo <- structure(list(), class = "foo")
class_foo <- new_S3_class("foo")

bar <- new_class("bar")

method(`+`, list(class_foo, class_any)) <- function(e1, e2) "success"

# Correct
foo + bar()
#> [1] "success"

# Can't find method?
foo + 10
#> Error in foo + 10: non-numeric argument to binary operator

This is not the case with regular S7 generics, which behave as expected.

fun <- new_generic("fun", c("e1", "e2"))

method(fun, list(e1 = class_foo, e2 = class_any)) <- function(e1, e2) "success"

fun(foo, bar())
#> [1] "success"
fun(foo, 10)
#> [1] "success"

Created on 2025-06-10 with reprex v2.1.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions