How to provide default value for implicit parameters at class level

后端 未结 2 1212
野趣味
野趣味 2021-02-01 17:57

I\'m trying to define a class with some methods taking an implicit parameter :

object Greetings {
  def say(name: String)(implicit greetings: String): String = g         


        
2条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 18:31

    I've found a workaround:

    class Greetings(implicit val greetings: String = "hello") {
        def say(name: String): String = greetings + " " + name 
    }
    

    Like this I can have a default value and override it if I want:

    new Greetings().say("loic")                     //> res0: String = hello loic
    
    implicit val greetings = "hi"                   //> greetings  : java.lang.String = hi
    new Greetings().say("loic")                     //> res1: String = hi loic
    
    new Greetings()("coucou").say("loic")           //> res2: String = coucou loic
    

    Note: new Greetings()("coucou") is working, not new Greetings("coucou") , because of a syntax strangeness explained here.

提交回复
热议问题