What is a «virtualType» and how to use it?

Look at the catalog_product_link widget declaration:

There is no class Magento\Catalog\Block\Product\Widget\Link, it is a virtual type:

So Magento\Catalog\Block\Product\Widget\Link is an alias to Magento\Catalog\Block\Widget\Link, but with a custom dependency injection: an argument entityResource has a type Magento\Catalog\Model\ResourceModel\Product.

Look at the Magento\Catalog\Block\Widget\Link constructor:

As you can see a normal Magento\Catalog\Block\Widget\Link instance will have an argument entityResource of type Magento\Catalog\Model\ResourceModel\AbstractResource.

By using virtualType declaration we inject the custom entityResource of type Magento\Catalog\Model\ResourceModel\Product.

Here is an explanation on StackExchange: http://magento.stackexchange.com/a/33140/18793

Example 2

Rewrite/Plugin does not work with virtualType. For example, I rewrite function _getProductCollection in magento/module-catalog/Block/Product/ListProduct.php does not work in page search result. Because page search uses a virtualType class which is defined in magento/module-catalog-search/etc/frontend/di.xml

What do you mean by “rewrite function”?

See also: