Shashank
Shashank

Reputation: 370

Scala implicit conversion: converting Int to List does not print list on printing the integer variable

I am experimenting with implicit conversion feature of scala.

I tried writing a method for implicit conversion from Int to List of three same integers

Although the list methods are applicable, but when we print the value it still shows as Integer

scala> implicit def conversion(x:Int) = List(x,x,x)
conversion: (x: Int)List[Int]

scala> 1
res31: Int = 1

scala> res31.length
res32: Int = 3

scala> res31.tail
res33: List[Int] = List(1, 1)

scala> println(res31)
1

Any ideas why it is showing such behavior? Ideally it should print like following:

List(1, 1, 1)

Upvotes: 0

Views: 67

Answers (4)

lovei
lovei

Reputation: 250

println expects an argument of type Any, so there is no need for implicit conversion. In the first two cases, Int does not have methods named length or tail but List has them, that's why conversion takes place in those expressions.

Upvotes: 1

Abhijit Nayak
Abhijit Nayak

Reputation: 101

To print as a list you can use, println(res53.toList)

Upvotes: 0

Georg Engel
Georg Engel

Reputation: 917

Implicit conversions do only kick in when the original value cannot be applied, e.g. there is no method with such parameter. Because you can print an Int there is "no need" for scala to apply a conversion. You can force it with: println(res31:List[Int])

Upvotes: 2

chengpohi
chengpohi

Reputation: 14217

See the document: http://docs.scala-lang.org/tutorials/tour/implicit-conversions.html

Implicit conversions are applied in two situations:

If an expression e is of type S, and S does not conform to the expression’s expected type T. In a selection e.m with e of type S, if the selector m does not denote a member of S.

so for your example, there is no type conversion occur except res31.tail, In res31.tail need to call List type tail method, this action trigger implicit conversion. the other actions not trigger implicit conversion.

Upvotes: 1

Related Questions