Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala implicit gets imported only on use

Tags:

scala

implicit

i'm new to scala and trying some handson exercises .

i'm trying to use implicits by placing implicits in a companion object . however , the compiler doesn't detect implicit unless it is used .

class ImplicitTest {
    import Implicits.implicitInt;
    println(implicitInt)
    def implicitm1(implicit i : Int) = 1
    println(implicitm1)
}
object Implicits {
    implicit val implicitInt = 1
}

This compiles fine . However if i comment out the third line

\\println(implicitInt)`

then i get a compile-time errors on

println(implicitm1)` 

which says

could not find implicit value for parameter i:Int`

not enough arguments for method implicit m1(implicit i:Int) . Unspecified value parameter i`

what did i do wrong here ?

Thanks in advance

like image 630
piyush tripathi Avatar asked Mar 15 '26 19:03

piyush tripathi


1 Answers

If you include the type for val implicitInt: Int = 1, it works. Issues like this are one of the reasons it's recommended to always specify types for implicits.

Scala type inference works from top to bottom, so in your case the compiler doesn't yet know this type when it gets to typechecking the println(implicitm1) line.

I guess that when you include println(implicitInt), the compiler is forced to find implicitInt's type at that line.

like image 175
Alexey Romanov Avatar answered Mar 18 '26 19:03

Alexey Romanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!