String in scala


#1

var x= "Scala"
println(x.getClass)

This prints:class java.lang.String

Does it mean every scala string is of type java.lang.String? Doesn’t scala have string class of its own?


#2

Yes, Scala String is an alias for java.lang.String.

type String = java.lang.String

Line 85: https://github.com/scala/scala/blob/v2.11.7/src/library/scala/Predef.scala

But Scala String has many more methods, for example, filter, map, etc.

https://www.scala-lang.org/api/2.12.x/scala/collection/immutable/StringOps.html

https://docs.oracle.com/javase/9/docs/api/java/lang/String.html


#3

OK. So I guess these extra methods are provided through implicits.


#4

Having incompatible String implementation would have too much drawbacks compared to possible advantages. Built-in Strings receive special JVM optimizations and are used everywhere. Incompatible Strings would need to be converted back and forth when interfacing with Java code - and you can’t use wrapper classes as String class is final so can’t be extended. Additionally, Java’s Strings are already immutable so they don’t make functional programming harder (in contrast to standard Java collections which aren’t a good choice for functional programming).


#5

Correct. By and large, Scala uses the underlying “Java” types (really, JVM-standard types) where appropriate, so that we can interoperate with other JVM languages more easily. It then often makes more methods available for those types by using typeclasses and implicits…


#6

Worth saying that it would actually be nicer if Scala had a distinct type.

Crummy API like "".split could be avoided. The implementation of scala.String as a string of the underlying platform should be a backend concern.

Really tired of hearing questions about confusing String#split, obviously. And it’s not a newbie issue. It is a terrible productivity drag on every user of the language. So highly paid Scala programmers also waste billable hours looking up the Java API b/c it’s terrible.


#7

What’s the issue with split?