Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are implicit objects?

Tags:

I was reading about type classes where implicit objects were mentioned:

object Math {   trait NumberLike[T] {     def plus(x: T, y: T): T     def divide(x: T, y: Int): T     def minus(x: T, y: T): T   }   object NumberLike {     implicit object NumberLikeDouble extends NumberLike[Double] {       def plus(x: Double, y: Double): Double = x + y       def divide(x: Double, y: Int): Double = x / y       def minus(x: Double, y: Double): Double = x - y     }     implicit object NumberLikeInt extends NumberLike[Int] {       def plus(x: Int, y: Int): Int = x + y       def divide(x: Int, y: Int): Int = x / y       def minus(x: Int, y: Int): Int = x - y     }   } } 

What are they? Where are they described? I only found definition of implicit classes on the web but not of implicit objects.

like image 311
jhegedus Avatar asked Mar 23 '14 14:03

jhegedus


People also ask

What are explicit objects?

explicit--Explicit objects are declared and created within the code of your JSP page, accessible to that page and other pages according to the scope setting you choose.

How many implicit objects are there in JSP?

There are 9 jsp implicit objects. These objects are created by the web container that are available to all the jsp pages. The available implicit objects are out, request, config, session, application etc.

What are implicit objects available in JSP?

These Objects are the Java objects that the JSP Container makes available to the developers in each page and the developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.

What is the use of out implicit object?

The out implicit object is an instance of a javax. servlet. jsp. JspWriter object and is used to send content in a response.


1 Answers

In Scala, objects and values are treated mostly the same. An implicit object can be thought of as a value which is found in the process of looking up an implicit of its type.

In your example, if one implicitly looks for a NumberLike type class with type parameter Double or Int, one will find NumberLikeDouble and NumberLikeInt.

implicit object NumberLikeDouble extends NumberLike[Double] 

is thus roughly the same as

implicit val NumberLikeDouble: NumberLike[Double] = new NumberLike[Double] { ...} 

or

implicit def NumberLikeDouble: NumberLike[Double] = new NumberLike[Double] { ...} 

Like a val, there is only a single value of that type and instantiation is not needed.


A simple use case:

import Math.NumberLike  def sum[A](x: A, y: A)(implicit nl: NumberLike[A]) = nl.plus(x, y)  sum(4, 5)   // finds NumberLikeInt 
like image 177
0__ Avatar answered Sep 24 '22 15:09

0__