ScalaFX – Using Methods with Ambiguous Signature

In Java there is a distinction between primitive types and their wrappers. For instance, int is a primitive type and Integer is its wrapper. In Scala they are expressed by the same type: Int. Using ScalaFX classes that are parametrized with type corresponding to Java wrapper type, like Integer, can lead to compilation errors.

Assume here that we are using a ListView that contains Int items, so we will have

val listView = new ListView[Int] { ... }

Consider method scrollTo. It has two variants scrollTo(Int index), that scrolls to item with given index, and scrollTo(T object), that scrolls to given item on the list. Since T is Int, we have two methods with the same signature. If we try to use scrollTo:

listView.scrollTo(5)

we will get compilation error:

    Error:(160, 16) ambiguous reference to overloaded definition,
        both method scrollTo in class ListView of type (o: Int)Unit
        and  method scrollTo in class ListView of type (index: Int)Unit
        match argument types (Int)
            listView.scrollTo(5)
                     ^

A work around is to use parameter names to disambiguate between invocations:

listView.scrollTo(index = 5)

Now the code will compile fine, and we will scroll by the list index (rather than item value).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: