一般狀況下咱們會把一些共用的字符串處理方法封裝到一個工具類中,好比StringUtils類。假定咱們實現了一個方法increment,它接收一個字符串,而後把字符串中的每個字符加1,而後返回新的字符串。要使用這個方法咱們須要調用:StringUtils.increment(s)。ide
可是Scala爲咱們提供了一種更加靈活的方式-隱式方法,它能夠直接讓你以"s.incrment"的方式進行調用,就好像String類爲咱們提供了這個方法同樣。工具
scala> implicit class StringUtils(s: String) { | def increment = s.map(c => (c + 1).toChar) | def decrement = s.map(c => (c - 1).toChar) | def hideAll = s.replaceAll(".", "*") | } defined class StringUtils scala> "HAL".increment res28: String = IBM scala> "IBM".decrement res29: String = HAL scala> "IBM".hideAll res30: String = ***