Write an implicit function which takes a string as a parameter and converts it to a CustomString

import
scala.language.implicitConversions

object
ImplicitConversion extends App

{

class CustomString(val s: String)

{

def
isNumeric = s forall Character.isDigit

}

implicit def Str CustomString (s1: String): String = new CustomerString(s)

val
output1 = “100”.isNumeric

val
output2 = “100s”.isNumeric

println(output1,
output2)

}

can u please help me figure out how to proceed.

A few advices for future questions:

  • Format your code, so it is readable.
  • Be specific about your problem.
  • If your code produces an error message, paste it too; and tell us if it is a compile time error or a runtime exception.

Anyways, right now I am on my phone, so I can’t play with the code. But, implicit conversions are not recommended, I would advice you to either provide a toCustomString extension method. Or maybe, just provide all the methods on CustomString as extension methods.


Edit

After fixing some typos your code had, it worked without any problems.

import scala.language.implicitConversions

object ImplicitConversion extends App {
  class CustomString(val s: String) {
    def isNumeric = s forall Character.isDigit
  }

  implicit def StrToCustomString(s: String): CustomString =
    new CustomString(s)

  val output1 = "100".isNumeric
  val output2 = "100s".isNumeric
  
  println(output1)
  println(output2)
}

You can see it running here

However, as I said, it would be better to use extension methods directly, like this:

object syntax {
  object string {
    implicit class CustomString(private val s: String) extends AnyVal {
      def isNumeric = s forall Character.isDigit
    }
  }
}

object Main extends App {
  import syntax.string._ // Provides the isNumeric extension method.

  val output1 = "100".isNumeric
  val output2 = "100s".isNumeric

  println(output1)
  println(output2)
}

You can see it running here.

2 Likes

thanks

thank you, It helps.