Could not find implicit value inside companion object in Scala Worksheet

后端 未结 2 1591
青春惊慌失措
青春惊慌失措 2020-12-21 17:31

I am trying to create a type class inside IntelliJ Scala Worksheet. So I started with trait like this

trait Show[A] {
  def show(a : A) : String
}

2条回答
  •  [愿得一人]
    2020-12-21 17:59

    Implicit resolution tries companion objects so your code seems ok. However for an object to become a companion it must satisfy the following two requirements

    1. A companion object is an object with the same name as a class or trait, and
    2. is defined in the same source file as the associated class or trait.

    The following warning means the second requirement is not satisfied:

    defined object Show
    warning: previously defined trait Show is not a companion to object Show.
    Companions must be defined together; you may wish to use :paste mode for this.
    

    To satisfy second requirement we have to use Plain evaluation model in Scala Worksheet, or :paste mode in Scala REPL.

    Scala Worksheet Plain evaluation model

    To define a companion object in IntelliJ Scala Worksheet change Run type to Plain like so

    1. Show Worksheet Settings
    2. Select tab Settings for *.sc
    3. Change Run type from REPL to Plain

    Scala REPL paste mode

    As per @jwvh suggestion, make sure to enter paste mode

    If a class or object has a companion, both must be defined in the same file. To define companions in the REPL, either define them on the same line or enter :paste mode.

    as demonstrated here.

提交回复
热议问题