Confused with "polymorphic expression cannot be instantiated to expected type"

903 views
Skip to first unread message

吕盛龙

unread,
Sep 4, 2014, 4:22:55 AM9/4/14
to scala...@googlegroups.com
Hi,

  I am a newbie in Scala world. 

  I have a question about the following compile error. What is reason of f1's error? And Why f2, f3, f4 can work? I have tried to search something relevant, but still failed to get clear of this. 

 
$ scala
Welcome to Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_55).
Type in expressions to have them evaluated.
Type :help for more information.
scala> def f1: String = List(1,2,3,1,2,3).toSet.size.toString
<console>:7: error: polymorphic expression cannot be instantiated to expected type;
 found   : [B >: Int]()String
 required: String
       def f1: String = List(1,2,3,1,2,3).toSet.size.toString
                                                     ^
scala> def f2 = List(1,2,3,1,2,3).toSet.size.toString
f2: String
scala> def f3: String = List(1,2,3,1,2,3).toSet[Int].size.toString
f3: String
scala> def f4: String = List(1,2,3,1,2,3).toSet.size.toString()
f4: String

Som Snytt

unread,
Sep 4, 2014, 1:30:14 PM9/4/14
to 吕盛龙, scala-user
That's pretty wild.

IIUC, the RHS of f1 looks like a method type which it tries to adapt to the required String, by looking for an implicit to do that.

But it won't use the normal built-in conversion (empty application, where parens are supplied).

scala> def f1: String = List(1,2,3,1,2,3).toSet.size.toString
<console>:7: error: polymorphic expression cannot be instantiated to expected type;
 found   : [B >: Int]()String
 required: String
       def f1: String = List(1,2,3,1,2,3).toSet.size.toString
                                                     ^

scala> implicit def helper(f: () => String): String = f()
warning: there was one feature warning; re-run with -feature for details
helper: (f: () => String)String


scala> def f1: String = List(1,2,3,1,2,3).toSet.size.toString
f1: String

The bit from -Ytyper-debug:

|    |    |    |    |    |    [search #1] start `def f1`, searching for adaptation to pt=scala.this.Function1[scala.this.Function0[lang.this.String],String] (silent: method f1 in $iw, a MethodSymbol with flags <method>) implicits disabled
|    |    |    |    |    |    [search #2] start `def f1`, searching for adaptation to pt=scala.this.Function1[scala.this.<byname>[scala.this.Function0[lang.this.String]],String] (silent: method f1 in $iw, a MethodSymbol with flags <method>) implicits disabled

<console>:7: error: polymorphic expression cannot be instantiated to expected type;


--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages