Scala implicit conversion problem

I am struggling with the issue of implicit Scala conversion. The following code snippet illustrates my problem:

import org.junit.{ Test, Before, After };

class ImplicitsTest {

    implicit def toStringWrapper(str: String) = new StringWrapper(str);

    @Test
    def test(){
        val res1: Predicate = "str" startsWith "other";
    }

}

class StringWrapper(str: String){

    def startsWith(other: String): Predicate = null;

}

trait Predicate

How to force the string literal "str" ​​to be implicitly converted toStringWrapper to get startWith to return Predicate instead of Boolean?

Sample code does not compile. I know that String already has a startWith method, I just want to use a different one, and I thought using implicit conversions might be a way to do this.

+3
source share
2 answers

Scala , - , , . , , .

: (1) (2) .

: , , , , , , , , , , ( ):

object ImplicitExample {
  class CustomString(s: String) {
    def original = s
    def custom = this
    def startsWith(other: String): Int = if (s.startsWith(other)) 1 else 0
  }
  implicit def string_to_custom(s: String) = new CustomString(s)
  implicit def custom_to_string(c: CustomString) = c.original

  def test = {
    println("This".custom.startsWith("Thi"))
    println("This".custom.length())
  }
}

scala> ImplicitExample.test
1
4

scala> 
+12

Scala , , .

String startsWith, . , "str".startsWith("other"); ( Boolean) Predicate. , .

, . , Scala , . Java String Scala (Seq), , , sorted, . :

scala> "string" sorted
res1: String = ginrst

, , Predef. : , :

scala> implicit def wrap(s: String) = new { def sorted = "Hi!" }
wrap: (s: String)java.lang.Object{def sorted: java.lang.String}

scala> "string" sorted
<console>:7: error: type mismatch;
 found   : java.lang.String
 required: ?{val sorted: ?}
 Note that implicit conversions are not applicable because they are ambiguous:
 ...
+2

Source: https://habr.com/ru/post/1768302/


All Articles