Scala配置步骤:
- 打开AndroidStudio新建一个项目,为了能够尽可能踩坑涨姿势,选择支持Kotlin。
- 只要正常的Android环境配置是OK,新建的项目肯定是没问题。配置如下:
- gradle verison 5.4.1
- kotlin version 1.3.50
- gradle build tools 3.5.2
- Scala配置
- 根目录gradle配置Scala plugin
classpath 'com.wire:gradle-android-scala-plugin:1.5.0' maven { url "https://dl.bintray.com/wire-android/third-party" }
- 项目gradle应用plugin
apply plugin: 'jp.leafytree.android-scala'
- 解决上述配置产生的问题
解决配置问题
apply plugin: 'jp.leafytree.android-scala' 的问题
* What went wrong:
A problem occurred evaluating project ':app'.
> Failed to apply plugin [id 'jp.leafytree.android-scala']
> Could not find matching constructor for: org.gradle.api.internal.file.DefaultSourceDirectorySetFactory(org.gradle.api.internal.file.BaseDirFileResolver, org.gradle.api.internal.file.collections.DefaultDirectoryFileTreeFactory)
应用Scala插件报错。
由于插件兼容的gradle过低导致的,降低项目配置的gradle version 即可。
gradle version 5.4.1 =》 4.10.2
PS: 由于Scala plugin 并未及时更新兼容最新版的Gradle version。SO 只能降低gradle 版本用来适配Scala plugin
gradle build tools 版本问题
* What went wrong:
A problem occurred evaluating project ':app'.
> Failed to apply plugin [id 'com.android.application']
> Minimum supported Gradle version is 5.4.1. Current version is 4.10.2. If using the gradle wrapper, try editing the distributionUrl in /Users/qq/git/android/ScalaDemo/gradle/wrapper/gradle-wrapper.properties to gradle-5.4.1-all.zip
降低gradle版本之后,需要同步降低 gradle build tools 3.5.2 =》 3.2.1
Kotlin 插件版本
* What went wrong:
A problem occurred configuring root project 'ScalaDemo'.
> Could not resolve all artifacts for configuration ':classpath'.
> Could not download httpclient.jar (org.apache.httpcomponents:httpclient:4.5.3)
> Could not get resource 'https://jcenter.bintray.com/org/apache/httpcomponents/httpclient/4.5.3/httpclient-4.5.3.jar'.
> Could not GET 'https://jcenter.bintray.com/org/apache/httpcomponents/httpclient/4.5.3/httpclient-4.5.3.jar'.
> Remote host closed connection during handshake
需要同步修改 kotlin gradle plugin 1.3.50 => 1.3.10
ScalaCompileOptions
No such property: useAnt for class: org.gradle.api.tasks.scala.ScalaCompileOptions
当出现如上报错时,在项目目录的dependencies中配置如下:
dependencies{
ScalaCompileOptions.metaClass.daemonServer = true
ScalaCompileOptions.metaClass.fork = true
ScalaCompileOptions.metaClass.useAnt = false
ScalaCompileOptions.metaClass.useCompileDaemon = false
}
Setup Scala SDK
当尝试创建一个Scala Class时,AS会提示缺少Scala 的SDK,为了便于IDE做提示,我们需要点击之后,选择指定的Scala版本。如指定:2.11.12
Hello Word
完成上述配置之后,使用AS作为IDE的配置基本上差不多了。在新建的Scala文件中让Word Hello起来!
在熟悉的源码目录 java
目录下创建一个Scala Class文件即可。
class HelloWord {
def hello(): Unit = {
println("Hello Scala! ")
}
}
然后通过AS默认生成的Java单元测试直接跑起来即可:
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
HelloWord().hello()
assertEquals(4, 2 + 2)
}
}
Hello Scala!
最终run的控制台中会输出如上。